Java reading file as byte array

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);

Источник

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.

Читайте также:  Learn scripting in python

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 Read File to Byte Array

When reading the contents of a file that is presented as a series of bytes, FileInputStream is helpful. The purpose of FileInputStream is to read byte sequences, including picture data. Try employing FileReader to read the flows of letters. The Java language came up with the read(byte[]) function of the FileInputStream class that is utilized to recite information from the input flow up to the document’s size. Then, transforms the bytes together into a byte array. We will be showing you some of the simple examples of Java to read the file contents in a byte array. Before taking a look at the Java code for reading a file to a byte array, we need to generate a Java file which will be used for coding. The Java code file should be created with the “.java” extension with the touch query on the command line. On using the “ls” list query, we have listed the insides of the home directory and found the “array.java” file in it.

Читайте также:  border-top-style

To read a file to a byte array, we must have some text file with contents in it. Therefore, we have been utilizing the “touch” instruction to create a text file this time: new.txt. On using the “ls” instruction, it is in the home folder and we have opened it with the text editor manually to add data to it.

Example # 01

Within this example, we added the three-line data in the new.txt text file and saved it in the same home directory as per the cat query. Then, we will be utilizing the FileInputStream() class to read data from the file stream and store it in a byte array.

As we are going to use the concept of streaming in this java code example, we have to import the File class and the FileInputStream class into the code. So, we have utilized the “import” keyword along with the name of a whole package to import both packages successfully: java.io.File, and java.io.FileInputStream. After the import of both the needed packages, we have been defining a new user-defined class “Array” that will be implementing our main() execution function.

Its main() function started with the creation of a File class object “f” by passing it a path for a file to be read as a byte array, new.txt. Then, an object “I” for the input stream has been generated using the “f” file object in the arguments of a FileInputStream() function. This object has created an input stream using which, we can read the file. After this, we have created a byte array “A” using the byte[] variable object using the length() function in it to set the length for a byte array the same as the file length. The input stream object “I” has been cast off to call the read() function of java passing it a byte array “A” to read data from the file and add it to byte array “A”.

Now, this byte array “A” has been passed the constructor of the String class to create a string of its content and save it to the String variable “val”. The string variable “val” will be used in the System.out.println() function statement to print the converted content of a file to a byte array on the shell screen. Let’s first save our code before running it.

After successfully saving our java code, we have been executing it at the console query area with the “java” keyword command. All the three lines from the file “new.txt” are displayed on the console screen after conversion into a byte array. This was the simplest way to do so.

Example # 02

Let’s take a look at another method to read a file to a byte array in java with a different file value. This time, we have updated the new.txt file as per the output of the “cat” instruction below. Now, our text file contains the set of some numbers on three separate lines.

We will be utilizing the readAllBytes() function of Java in this example to read the file in a byte array. For this, we have imported all the necessary packages of java. The very first and main package is the “java.io” that has been importing all its sub-classes via the “*” character. After this, IOException class from the java.io package has been imported to use exception handling in the java code.

Читайте также:  Получить названия всех переменных python

After that, we have been importing the Arrays() class from the util package of Java and imported the sub-classes “Files”, “Path”, and “Paths” from the “file” class of a “nio” package. We have been naming the new class as “Array” and using the main() function in it. The Path() class has been creating an object “p” that has been getting the path of a text file “new.txt” from the get function of a Paths class. The object path “p” has been passed to the readAllBytes() function from the Files class to convert the data of a file to a byte array “A”.

In the end, the println() statement has been here to convert the byte array to string using the toString() function of an Arrays() class.

We have the data displayed as a String after conversion from a byte array on execution.

Conclusion

Here we have discussed the importance of FileInputStream class of Java. We have also discussed the use of its read() function to read the data of a file to a byte array. After this, we have discussed two methods to read file data into a byte array. The first example contains the use of the read function of FileInputStream class and the other contains the use of the readAllBytes() function of the Files class of java to do so. Using both these methods, we have provided a variety for our Java users to understand and utilize this concept.

About the author

Saeed Raza

Hello geeks! I am here to guide you about your tech-related issues. My expertise revolves around Linux, Databases & Programming. Additionally, I am practicing law in Pakistan. Cheers to all of you.

Источник

Convert File to a Byte Array in Java

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);  > > 

Related Article — Java File

Источник

Оцените статью