- 7 Examples to Read File into a byte array in Java
- 7 ways to read a file into a byte array in Java
- 1) Using Apache Commons IOUtils
- 2) Using Apache Commons FileUtils
- 3) Using FileInputStream and JDK
- Read File to Byte[] in Java
- Read Bytes From a File in Java
- Use FileInputStream to Read Bytes From a File in Java
- Use the Files Class readAllBytes() Method to Read Bytes From a File in Java
- Use Apache Commons-IO to Read Bytes From a File in Java
- Related Article — Java Bytes
- Related Article — Java File
7 Examples to Read File into a byte array in Java
Hello guys, Java programmers often face scenarios in real-world programming, where they need to load data from a file into a byte array, it could be text or binary file. One example is to convert the contents of a file into String for display. Unfortunately, Java’s File class, which is used to represent both files and directories, doesn’t have a method say toByteArray() . It only holds path and allows you to perform certain operations like opening and closing file, but doesn’t allow you to directly convert File to a byte array. Anyway, no need to worry as there are several other ways to read File into a byte array and you will learn those in this Java file tutorial.
If you are a fan of Apache commons and Google Guava like me, then you may already familiar with one-liner code, which can quickly read a file into a byte array; if not, then this is the right time to explore those API. In this tutorial, we are going to see 7 different examples to read File to a byte array, some by using third party libraries, and others by using JDK 6 and JDK 7 core Java libs. Depending upon your choice, you can use any of the following methods to convert file data into bytes. One thing to keep in mind is what you are doing with byte array; if you are creating String from a byte array, then beware with character encoding. You may need to find out correct character encoding by reading metadata information like Content-Type of HTML pages and of XML documents. While reading XML documents, it’s a bad idea to first read an XML file and store it in a String. Instead, it’s better to pass InputStream to XML parsers, and they will figure out the encoding themselves correctly.
One more thing to note is that you cannot read file larger than 2GB into a single byte array, you need multiple byte arrays for that. This limitation comes from the fact that the array index in Java is of int type, whose maximum value is 2147483647 , roughly equivalent to 2GB. Btw, I am expecting that you are familiar with basic Java Programing and Java API in general.
7 ways to read a file into a byte array in Java
Without wasting any more of your time, here are all the seven ways to load a file into a byte array in Java:
1) Using Apache Commons IOUtils
This is one of the easiest ways to read a file data into a byte array, provided you don’t hate third-party libraries. It’s productive because you don’t need to code it from scratch, worrying about exception handling, etc.
The IOUtils.toByteArray(InputStream input) Gets the contents of an
InputStream as a byte[]. This method also buffers the input internally, so there is no need to use a BufferedInputStream , but it’s not null-safe. It throws NullPointerException if the input is null .
2) Using Apache Commons FileUtils
The FileUtils class from org.apache.commons.io package provides a general file manipulation facility like writing to a file or reading from a file. This method is used to read the contents of a file into a byte array, and the good thing about this is that the file is always closed.
3) Using FileInputStream and JDK
This is the classic way of reading the file’s content into a byte array. Don’t forget to close the stream once done. Here is the code to read a file into a byte array using FileInputStream class in Java:
Read File to Byte[] in Java
In Java, reading a file to byte array may be needed in various situations. For example, passing the information through the network and other APIs for further processing.
Let’s learn about a few ways of reading data from files into a byte array in Java.
1. Using Files.readAllBytes()
The Files.readAllBytes() is the best method for using Java 7, 8 and above. It reads all bytes from a file and closes the file. The file is also closed on an I/O error or another runtime exception is thrown.
This method read all bytes into memory in a single statement so do not use it to read large files, else you may face OutOfMemoryError.
Path path = Paths.get("C:/temp/test.txt"); byte[] data = Files.readAllBytes(path);
Use FileInputStream for reading the content of a file when you already have the InputStream reference. Don’t forget to close the stream once the reading is done; else use try-with-resources block.
File file = new File("C:/temp/test.txt"); byte[] bytes = new byte[(int) file.length()]; try(FileInputStream fis = new FileInputStream(file))
3. Using Apache Commons IO
Another good way to read data into a byte array is in the apache commons IO library. It provides several useful classes for dealing with IO operations.
In the following example, we are using the FileUtils class to read the file content into byte array. The file is always closed either success or read error.
byte[] bytes = FileUtils.readFileToByteArray(file);
A similar class is IOUtils which can be used in the same way.
byte[] bytes = IOUtils.toByteArray(new FileInputStream(file));
Another good way to read data into a byte array is in Google Guava library.
The following example uses the com.google.common.io.Files class to read the file content into a byte array.
byte[] bytes3 = com.google.common.io.Files.toByteArray(file);
Read Bytes From a File in Java
- Use FileInputStream to Read Bytes From a File in Java
- Use the Files Class readAllBytes() Method to Read Bytes From a File in Java
- Use Apache Commons-IO to Read Bytes From a File in Java
There are several methods in Java to read bytes from a file or to convert a file into bytes or bytes array. This tutorial demonstrates different methods to read bytes from a file in Java.
Use FileInputStream to Read Bytes From a File in Java
The FileInputStream can read data from the given file using bytes. We can use this class’s FileInputStream.read() method to read the bytes from a file in Java.
- First, create an instance of the FileInputStream class.
- Now, create a byte array. The length should be the same as the input file.
- Read the bytes from FileInputStream using read() method.
- Print the byte array.
- Close the instance.
Let’s try to implement an example based on the above steps.
Our input file is in Rich Text Format .
Hi, This is delftstack.com! The Best tutorial site.
package delftstack; import java.io.*; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; public class Example public static void main(String[] args) throws IOException File File_Path = new File("C:\\Users\\Sheeraz\\delftstack.rtf"); // Instance of the FileInputStream FileInputStream File_Input_Stream = new FileInputStream(File_Path); // Create a byte array byte[] Demo_Array = new byte[(int)File_Path.length()]; // Read file content to byte array File_Input_Stream.read(Demo_Array); //Close the instance File_Input_Stream.close(); // Print the above byte array System.out.print(Arrays.toString(Demo_Array)); > >
The code above will read the bytes from the given file into an array. See output:
[72, 105, 44, 32, 84, 104, 105, 115, 32, 105, 115, 32, 100, 101, 108, 102, 116, 115, 116, 97, 99, 107, 46, 99, 111, 109, 33, 32, 84, 104, 101, 32, 66, 101, 115, 116, 32, 116, 117, 116, 111, 114, 105, 97, 108, 32, 115, 105, 116, 101, 46]
Use the Files Class readAllBytes() Method to Read Bytes From a File in Java
- Get the path using the Paths.get() method.
- Read the bytes from the given file using Files.readAllBytes() into an array.
- Print the byte array.
package delftstack; import java.io.*; 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 Example public static void main(String[] args) throws IOException // Create the path Path File_Path = Paths.get("C:\\Users\\Sheeraz\\delftstack.rtf"); // Read Bytes byte[] Demo_Array = Files.readAllBytes(File_Path); // Print the above byte array System.out.print(Arrays.toString(Demo_Array)); > >
The code will read the bytes from the given file using the Files.readAllBytes() method. See output:
[72, 105, 44, 32, 84, 104, 105, 115, 32, 105, 115, 32, 100, 101, 108, 102, 116, 115, 116, 97, 99, 107, 46, 99, 111, 109, 33, 32, 84, 104, 101, 32, 66, 101, 115, 116, 32, 116, 117, 116, 111, 114, 105, 97, 108, 32, 115, 105, 116, 101, 46]
Use Apache Commons-IO to Read Bytes From a File in Java
The Apache Commons-IO has a package, FileUtils , which can be used to read all the bytes from a file in Java. Make sure Apache Commons-IO is added to your Java environment.
Here is the maven dependency for Apache Commons-IO ; add it to your pom.xml .
- Create a file using the File class with the given path.
- Read the Bytes using the FileUtils.readFileToByteArray() with the file name as an input.
- Print the byte array.
Here is the Java implementation for this example.
package delftstack; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.util.Arrays; public class Example public static void main(String[] args) throws IOException // Create the path File Demo_File = new File("C:\\Users\\Sheeraz\\delftstack.rtf"); // Read Bytes byte[] Demo_Array = FileUtils.readFileToByteArray(Demo_File); // Print the above byte array System.out.print(Arrays.toString(Demo_Array)); > >
The code will read the bytes from the given file using the Apache Commons-IO library. See output:
[72, 105, 44, 32, 84, 104, 105, 115, 32, 105, 115, 32, 100, 101, 108, 102, 116, 115, 116, 97, 99, 107, 46, 99, 111, 109, 33, 32, 84, 104, 101, 32, 66, 101, 115, 116, 32, 116, 117, 116, 111, 114, 105, 97, 108, 32, 115, 105, 116, 101, 46]
Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.