Reading file into bytearrayoutputstream

This is an example of reading file into bytearrayoutputstream.

How to read file into bytearrayoutputstream

This tutorial shows you how to read file using byteinputstream and then write to another file using bytearrayoutputstream. This example code is very helpful in learning the concept of byte input stream and byte output stream. This is and good example of reading file into bytearrayoutputstream.

This example will teach you how you can read the file into byte array and then write byte array data into a file.

In this example we have used the class InputStream for reading the file content into byte array. The read (byte[] bytes) is used to read the data into byte array. Our example reads the data using read(byte[] bytes) method and then using FileOutputStream class writes the data into a new file.

The fileOutputStream.write(bytes) of the FileOutputStream class is used to write the bytes data into a file.

Here is the code of the example program:


* Example of Reading file into byte array and then write byte array into a file

public class ReadingFileToByteArrayOutputStream 
	public static void main(String[] args) 

		System.out.println("Example of Reading file into byte array and then write byte array into a file");
		//Instantiate the file object
		File file = new File("test.text");
		//Instantiate the input stread
		InputStream insputStream = new FileInputStream(file);
		long length = file.length();
		byte[] bytes = new byte[(int) length];;
		//Write the bytes to a file
		FileOutputStream fileOutputStream = new FileOutputStream("test2.text");

		}catch(Exception e){
			System.out.println("Error is:" + e.getMessage());


Read more at Java File - Example and Tutorials.

Share on Google+Share on Google+

Reading file into bytearrayoutputstream

Posted on: January 18, 2013 If you enjoyed this post then why not add us on Google+? Add us to your Circles



Discuss: Reading file into bytearrayoutputstream  

Post your Comment

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