June 23, 2022

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. See example.
  2. Java 7 onward you can use Files.readAllBytes() method which reads all the bytes from a file and return a byte array. See example.
  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. See example.

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

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;

public class FileToBytearray {
  public static void main(String[] args) {
    File file = new File("D:\\test.txt");
    byte[] bArray = convertFileToByteArray(file);
    System.out.print(Arrays.toString(bArray));
  }
	
  private static byte[] convertFileToByteArray(File file){
    FileInputStream fis = null;
    // Creating bytearray of same length as file
    byte[] bArray = new byte[(int) file.length()];
    try{
      fis = new FileInputStream(file);
      // Reading file content to byte array
      fis.read(bArray);
      fis.close();                    
    }catch(IOException ioExp){
      ioExp.printStackTrace();
    }finally{
      if(fis != null){
        try {
          fis.close();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }
    return bArray;
  }
}
Output
[49, 48, 48, 49, 124, 49, 48, 48, 51, 124, 50, 48, 48, 48, 13, 10, 49, 
48, 48, 54, 124, 50, 48, 48, 52, 124, 51, 48, 48, 48, 13, 10, 49, 48, 
48, 53, 124, 49, 48, 48, 55, 124, 49, 48, 48, 48, 48, 13, 10, 84, 104, 
105, 115, 32, 105, 115, 32, 97, 32, 116, 101, 115, 116, 32, 108, 105, 
110, 101, 46, 10, 76, 105, 110, 101, 32, 119, 114, 105, 116, 116, 101, 
110, 32, 98, 121, 32, 74, 97, 118, 97, 32, 112, 114, 111, 103, 114, 97, 
109, 32, 105, 110, 32, 107, 110, 112, 67, 111, 100, 101, 46, 99, 111, 
109, 46]

As you can see output is a series of bytes.

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

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;

public class FileToBytearray {
  public static void main(String[] args) {       
    Path path = Paths.get("D:\\test.txt");
    try {
      byte[] bArray = Files.readAllBytes(path);
      System.out.println(Arrays.toString(bArray));
    } catch (IOException e) {
      System.out.println("Error while converting " + e.getMessage());
    }    
  }
}

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
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import org.apache.commons.io.IOUtils;

public class FileToBytearray {
  public static void main(String[] args) {       
    File file = new File("D:\\test.txt");
    try(FileInputStream fis = new FileInputStream(file)) {
      byte[] bArray;
      bArray = IOUtils.toByteArray(fis);
      System.out.println(Arrays.toString(bArray));
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}
Using FileUtils.readFileToByteArray
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import org.apache.commons.io.FileUtils;

public class FileToBytearray {
  public static void main(String[] args) {       
    File file = new File("D:\\test.txt");
    byte[] bArray;
    try {
      bArray = FileUtils.readFileToByteArray(file);
      System.out.println(Arrays.toString(bArray));
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }	
  }
}

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

No comments:

Post a Comment