- Tech Tutorials
- Friday, March 3, 2023
- Java Program to Convert a File to Byte Array
- Available options for conversion
- 1. File to byte[] using read method of FileInputStream
- 2. File to byte array conversion using Files.readAllBytes()
- 3. Using IOUtils.toByteArray() and FileUtils.readFileToByteArray() methods
- 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
- Java Program to Convert File to byte array and Vice-Versa
- Steps to convert File to byte array :
- Pseudo code for the above algorithm :
- Example 1 : File to byte array
- Read File to Byte[] in Java
- Convert File to a Byte Array in Java
- Use readAllBytes() to Convert a File to Byte Array in Java
- Use FileUtils.readFileToByteArray() to Convert a File to Byte Array in Java
- Related Article — Java File
Tech Tutorials
Tutorials and posts about Java, Spring, Hadoop and many more. Java code examples and interview questions. Spring code examples.
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
- Using read method of the FileInputStream class. See example.
- Using Files.readAllBytes() method Java 7 onward. See example.
- Using IOUtils.toByteArray() method provided by Apache commons IO. See example.
- 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
- 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!
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:
Java Program to Convert File to byte array and Vice-Versa
A byte array is a collection of bytes, often used to store binary data. It can be used to store data in memory, or to read and write data to a file or network stream. In programming languages such as C#, Java and Python, byte arrays are often used to store and manipulate binary data such as images, audio and video files.
Steps to convert File to byte array :
- For the file you want to convert, create a File object.
- Making use of the File object produced in step 1, create a FileInputStream object.
- Create a byte array with the file’s length in it.
- To read the file’s contents into the byte array, use the read() function of the FileInputStream object.
- FileInputStream object should be closed.
Pseudo code for the above algorithm :
// Create a File object for the file you want to convert File file = new File("path/to/myfile.txt"); try < // Create a FileInputStream object using the File object FileInputStream fis = new FileInputStream(file); // Create a byte array with the length of the file byte[] byteArray = new byte[(int)file.length()]; // Use the read() method of the FileInputStream object to read the contents of the file into the byte array fis.read(byteArray); // Close the FileInputStream object fis.close(); // Use the byte array as needed // . >catch (IOException e) < // Handle the exception e.printStackTrace(); >
Note : This pseudocode creates a File object for the file we want to convert, makes a FileInputStream object using the File object, creates a byte array with the file’s length, reads the file’s contents into the byte array using the FileInputStream’s read() method, closes the FileInputStream, and then uses the byte array as needed. Because this is only pseudocode and not actual code, it might need to be significantly altered to function in a particular programming environment.
Example 1 : File to byte array
import java.io.*; public class Main < public static void main(String[] args) < // Create a File object File file = new File("path/to/myfile.txt"); try < // Read the file into a byte array FileInputStream fileInputStream = new FileInputStream(file); byte[] byteArray = new byte[(int)file.length()]; fileInputStream.read(byteArray); fileInputStream.close(); // Use the byte array as needed // . >catch (IOException e) < e.printStackTrace(); >> >
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);
Convert File to a Byte Array in Java
- 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); > >