Reading 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 as well as other APIs for further processing.

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

1. Files.readAllBytes() – Java 8

Files.readAllBytes() is best method if you are using Java 7, 8 and above.

Example 1: Reading file to byte[]

Path path = Paths.get("C:/temp/test.txt");
byte[] data = Files.readAllBytes(path);

Read More: 3 ways to read files using Java NIO

2. FileInputStream – Java 6

Use for reading the content of a file in Java 6.

Example 2: Reading a file byte by byte

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

   //Read bytes with InputStream
   fileInputStream = new FileInputStream(file);;

   for (int i = 0; i < bFile.length; i++)
      System.out.print((char) bFile[i]);
catch (Exception e)

3. FileUtils, IOUtils – Apache Commons IO

Another good way to read data into a byte array is in apache commons IO library.

Example 3: Reading an entire file into byte[]

//Using FileUtils.readFileToByteArray()
byte[] file)
//Using IOUtils.toByteArray
byte[] input) 

4. Files, ByteStreams – Guava

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

Example 4: Reading an entire file into byte[]

//Using Files.toByteArray()
byte[] file)
//Using ByteStreams.toByteArray
byte[] is)

Happy Learning !!

Source Code on Github

Leave a Reply

Most Voted
Newest Oldest
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