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 java.io.FileInputStream 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()];

try
{
   //Read bytes with InputStream
   fileInputStream = new FileInputStream(file);
   fileInputStream.read(bFile);
   fileInputStream.close();

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

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[] org.apache.commons.io.FileUtils.readFileToByteArray(File file)
 
//Using IOUtils.toByteArray
byte[] org.apache.commons.io.IOUtils.toByteArray(InputStream 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[] com.google.common.io.Files.toByteArray(File file)
 
//Using ByteStreams.toByteArray
byte[] com.google.common.io.ByteStreams.toByteArray(InputStream is)

Happy Learning !!

Source Code on Github

Leave a Reply

2 Comments
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