Home Java Javafile Reading binary file into byte array in Java



Reading binary file into byte array in Java
Posted on: January 18, 2013 at 12:00 AM
This example is about 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.

Related Tags for Reading binary file into byte array in Java:


More Tutorials from this section

Ask Questions?    Discuss: Reading binary file into byte array in Java  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.