Convert File to a Byte Array in Java

  1. Use readAllBytes() to Convert a File to Byte Array in Java
  2. Use FileUtils.readFileToByteArray() to Convert a File to Byte Array in Java

This tutorial discusses methods to convert a file to byte array in Java.

Use readAllBytes() to Convert a File to Byte Array in Java

The simplest way to convert a file to byte array in Java is to use the readAllBytes() method provided by the Files class. In the example below, we will first read a file and then convert it to a byte array.

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;

public class MyClass {
    public static void main(String args[]) throws IOException {
        File file = new File('sample.txt')
        byte[] fileContent = Files.readAllBytes(file.toPath());
    }
}

Use FileUtils.readFileToByteArray() to Convert a File to Byte Array in Java

Another method to convert a file to byte array in Java is to use FileUtils.readFileToByteArray() provided by Apache Commons File Utils. The below example illustrates this:

import org.apache.commons.io.FileUtils;

public class MyClass {
    public static void main(String[] args) throws IOException {
        File file = new File('sample.txt');
        byte[] fileContent = FileUtils.readFileToByteArray(file);
    }
}
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Java File

  • Check if a File Exists in Java