Home Java Javafile Reading file into bytearrayoutputstream
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Reading file into bytearrayoutputstream

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

import java.io.*;

/**
* 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");
		try{
		//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];

		insputStream.read(bytes);
		insputStream.close();
	
		//Write the bytes to a file
		FileOutputStream fileOutputStream = new FileOutputStream("test2.text");
		fileOutputStream.write(bytes);

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

	}
}

Read more at Java File - Example and Tutorials.

Advertisements

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

Ask Questions?    Discuss: Reading file into bytearrayoutputstream  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com