Friday, March 3, 2023

Java Program to Convert a File to Byte Array

There are times when we need to read file content into a byte array like when we need to send the file content over the network or we need to calculate check sum using file data. So in this post we'll see various ways to convert file to a byte array in Java.

Available options for conversion

  1. Using read method of the FileInputStream class. See example.
  2. Using Files.readAllBytes() method Java 7 onward. See example.
  3. Using IOUtils.toByteArray() method provided by Apache commons IO. See example.
  4. Using FileUtils.readFileToByteArray method provided by Apache commons IO. See example.

1. File to byte[] using read method of FileInputStream

You can use java.io.FileInputStream to read file content into a byte array using the read() method. General structure and description of read method as per Java docs is as given below.

public int read(byte[] b) throws IOException

Reads up to b.length bytes of data from this input stream into an array of bytes. This method blocks until some input is available.

public class FileToByteArrayDemo {
  public static void main(String[] args) {
    File file = new File("F:\\NetJS\\Articles.txt");
    // Using java.io.FileInputStream
    byte[] bArray = readFileToByteArray(file);
    //displaying content of byte array
    for (int i = 0; i < bArray.length; i++){
      System.out.print((char) bArray[i]);
    }  
  }
    
  /**
   * This method uses java.io.FileInputStream to read
   * file content into a byte array
   * @param file
   * @return
   */
  private static byte[] readFileToByteArray(File file){
    FileInputStream fis = null;
    // Creating a byte array using the length of the file
    // file.length returns long which is cast to int
    byte[] bArray = new byte[(int) file.length()];
    try{
      fis = new FileInputStream(file);
      fis.read(bArray);
      fis.close();                   
    }catch(IOException ioExp){
      ioExp.printStackTrace();
    }
    return bArray;
  }
}

2. File to byte array conversion using Files.readAllBytes()

Java 7 onward you can use static method readAllBytes(Path path) in the Files class for converting file to byte array.

public class FileToByteArrayDemo {
  public static void main(String[] args) {              
    Path path = Paths.get("F:\\NetJS\\Articles.txt");
    try {
      byte[] bArray = Files.readAllBytes(path);
      // reading content from byte array
      for (int i = 0; i < bArray.length; i++){
        System.out.print((char) bArray[i]);
      }
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }       
  }
}

3. Using IOUtils.toByteArray() and FileUtils.readFileToByteArray() methods

Apache commons IO also provides utility methods to read file content into a byte array.

  • IOUtils.toByteArray- Takes FileInputStream object as param.
  • FileUtils.readFileToByteArray- Takes File object as param.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

public class FileToByteArrayDemo {
  public static void main(String[] args) {
    File file = new File("F:\\NetJS\\Articles.txt");        
    // Using ApacheCommons methods
    readToByteArrayUsingCommons(file);     
  }
    
  /**
   * This method uses apache commons to read
   * file content into a byte array
   * @param file
  */
  private static void readToByteArrayUsingCommons(File file){
    try(FileInputStream fis = new FileInputStream(file)) {
      // Using IOUtils method, it takes FileInputStream 
      // object as param
      byte[] bArray = IOUtils.toByteArray(fis);
      for (int i = 0; i < bArray.length; i++){
        System.out.print((char) bArray[i]);
      }
      // Using FileUtils method, it takes file object
      // as param
      bArray = FileUtils.readFileToByteArray(file);
      //displaying byte array content
      for (int i = 0; i < bArray.length; i++){
        System.out.print((char) bArray[i]);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }        
  }
}

Note that in the method readToByteArrayUsingCommons I have used try-with-resources which is available from Java 7. Closing the input stream will be done automatically by try-with-resources.

Refer try-with-resources in Java 7 to know more about try-with-resources.

That's all for this topic Java Program to Convert a File to Byte Array. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Reading File in Java Using Scanner
  2. Reading File in Java Using BufferedReader
  3. How to Read Input From Console in Java
  4. Write to a File in Java
  5. Unzip File in Java

You may also like-

  1. Convert String to Byte Array Java Program
  2. Count Number of Words in a String Java Program
  3. How to Remove Elements From an Array Java Program
  4. Java Program to Check Prime Number
  5. final Keyword in Java With Examples
  6. How to Loop Through a Map in Java
  7. Java ReentrantLock With Examples
  8. Dependency Injection in Spring Framework