How to Convert File to Byte Array in Java

This post shows different ways to convert file to byte array in Java.

  1. You can use read(byte[] b) method of FileInputStream class which reads up to b.length bytes of data from this input stream into byte array.
  2. Java 7 onwards you can use Files.readAllBytes() method which reads all the bytes from a file and return a byte array.
  3. Apache CommonsIO also has methods IOUtils.toByteArray and FileUtils.readFileToByteArray to convert file to byte array. To use it you will have to put CommonsIO jar in your project’s classpath.

Java program to convert file to byte array

Let’s see examples of converting file to byte array in Java using the above mentioned options.

Using read method of FileInputStream class

Output

As you can see output is a series of bytes.

Using Files.readAllBytes() method to convert file to byte array

Using Apache CommonsIO utility methods

As already mentioned there are two methods that can be used for converting file to byte array if Apache CommonsIO is used.

  • IOUtils.toByteArray – This method takes FileInputStream object as argument.
  • FileUtils.readFileToByteArray – Pass instance of File as argument.

Using IOUtile.toByteArray

Using FileUtils.readFileToByteArray

That’s all for the topic How to Convert File to Byte Array in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.