Convert File to a Byte Array in Java
Hassan Saeed
Jan 30, 2023
Oct 05, 2020
-
Use
readAllBytes()
to Convert a File to Byte Array in Java -
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);
}
}
Related Article - Java File
- Remove Line Breaks Form a File in Java
- FileFilter in Java
- File Separator in Java
- Get File Size in Java
- Read Bytes From a File in Java
- Delete Files in a Directory Using Java