Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Java Javafile Reading binary file into byte array in Java

Related Tutorials


 
 

Share on Google+Share on Google+

Reading binary file into byte array in Java

Advertisement
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.

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: January 18, 2013

Related Tutorials

Discuss: Reading binary file into byte array in Java  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:1
sandeep
November 20, 2013
Thank you

Thanks a lot.. Really helpful for beginners..
DMCA.com