The following example shows you how to read file contents into byte
array. We use the IOUtils
class of the commons-io
library.
package org.kodejava.commons.io;
import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class FileToByteArray {
public static void main(String[] args) {
File file = new File("README.md");
try {
InputStream is = new FileInputStream(file);
byte[] bytes = IOUtils.toByteArray(is);
System.out.println("Byte array size: " + bytes.length);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Maven Dependencies
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
Latest posts by Wayan (see all)
- How do I split large excel file into multiple smaller files? - April 15, 2023
- How do I get the number of processors available to the JVM? - March 29, 2023
- How do I show Spring transaction in log / console? - March 29, 2023