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

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

2 thoughts on “Reading File to Byte[] in Java”

  1. 1 )Write a code which will construct a line for me two points ( .————————.) ?
    Output should be “these line is made my these two points”

    2) I have one Bottle object.I want to design all the oops concepts using that object can anyone explain me ?


Leave a Comment


A blog about Java and related technologies, the best practices, algorithms, and interview questions.