Read File to Byte[] in Java

In Java, reading a file to byte array may be needed in various situations. For example, passing the information through the network and other APIs for further processing.

Let’s learn about a few ways of reading data from files into a byte array in Java.

1. Using Files.readAllBytes()

The Files.readAllBytes() is the best method for using Java 7, 8 and above. It reads all bytes from a file and closes the file. The file is also closed on an I/O error or another runtime exception is thrown.

This method read all bytes into memory in a single statement so do not use it to read large files, else you may face OutOfMemoryError.

Path path = Paths.get("C:/temp/test.txt");

byte[] data = Files.readAllBytes(path);

2. Using FileInputStream

Use FileInputStream for reading the content of a file when you already have the InputStream reference. Don’t forget to close the stream once the reading is done; else use try-with-resources block.

File file = new File("C:/temp/test.txt");
byte[] bytes = new byte[(int) file.length()];

try(FileInputStream fis = new FileInputStream(file)) {
  fis.read(bytes);
}

3. Using Apache Commons IO

Another good way to read data into a byte array is in the apache commons IO library. It provides several useful classes for dealing with IO operations.

In the following example, we are using the FileUtils class to read the file content into byte array. The file is always closed either success or read error.

byte[] bytes = FileUtils.readFileToByteArray(file);

A similar class is IOUtils which can be used in the same way.

byte[] bytes = IOUtils.toByteArray(new FileInputStream(file));

4. Using Guava

Another good way to read data into a byte array is in Google Guava library.

The following example uses the com.google.common.io.Files class to read the file content into a byte array.

byte[] bytes3 = com.google.common.io.Files.toByteArray(file);

Happy Learning !!

Source Code on Github

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode