Reading binary file into byte array in Java

This example is about reading binary file into byte array in Java

Reading binary file into byte array in Java

This example is about reading binary file into byte array in Java

Reading binary file into byte array in Java

Example code of reading binary file into byte array in Java

This example shows you how to read a binary file into byte array from Java program. This type of example code is need where you have to read the binary data into byte array and use the byte array data for further processing.

To the binary file into byte array we will use the class InputStream of java.io package. This class is providing read() method with reads the data into byte stream.

Following line of code can be used:

insputStream.read(bytes);

Here is the complete code of the Java program that reads the binary file into byte array:

import java.io.*;

public class ReadingBinaryFileIntoByteArray
{
	public static void main(String[] args) 
	{
		System.out.println("Reading binary file into byte array example");
		try{
		//Instantiate the file object
		File file = new File("test.zip");
		//Instantiate the input stread
		InputStream insputStream = new FileInputStream(file);
		long length = file.length();
		byte[] bytes = new byte[(int) length];

		insputStream.read(bytes);
		insputStream.close();
	
		String s = new String(bytes);
		//Print the byte data into string format
		System.out.println(s);
		}catch(Exception e){
			System.out.println("Error is:" + e.getMessage());
		}
	}
}

Read more examples at Java File - Example and Tutorials.