How to copy data from a file to another file in java.

How to copy data from a file to another file in java.


Posted in : Core Java Posted on : October 21, 2010 at 12:30 PM Comments : [ 0 ]

In this example, you will see how to copy content of a file into another file in java.

How to copy data from a file to another file in java.

In this example, you will see how to write data into another file using a BufferedOutputStream class in java. BufferedInputStream is a class, that reads characters from a stream and stores it in an internal buffer. It reads the byte from file input stream. The input stream is a file "TestFile.txt". The read() method reads the bytes from the input stream. And the BufferedOutputStream class creates a output stream. The write() method of BufferedOutputStream class write bytes.

Code:
CopyDataToAnoterFile.java
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class CopyDataToAnoterFile{

public static void main(String[] args) throws Exception {
		File file = new File("TestFile.txt");
		FileInputStream fileInStream = new FileInputStream(file);
		BufferedInputStream bufferInStream = new BufferedInputStream(
				fileInStream);

		FileOutputStream fileOutputStream = new FileOutputStream(
		"TestFileWrite.txt");
		BufferedOutputStream bOutputStream = new BufferedOutputStream(
				fileOutputStream);
		byte[] barray = new byte[1024];
		while (( bufferInStream.read(barray)) != -1) {
			bOutputStream.write(barray);
			System.out.println("Data successfully written in another file.");
		}
		bufferInStream.close();
		bOutputStream.close();
	}
}
Output:
Data successfully written in another file.

Download this code.

Go to Topic «PreviousHomeNext»

Your Comment:


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

 
Tutorial Topics