Home Tutorial Java Io Copy one file into another

 
 

Copy one file into another
Posted on: February 17, 2011 at 12:00 AM
Advertisement
In this section, you will learn how to copy content of one file into another file

Copy one file into another

In this section, you will learn how to copy content of one file into another file. We will perform this operation by using the read & write methods of BufferedWriter class.

Given below example will give you a clear idea :

Example :

import java.io.*;

public class CopyFile {
public static void main(String[] args) throws Exception {
BufferedWriter bf = new BufferedWriter(new FileWriter("source.txt"));
bf.write("This string is copied from one file to another\n");
bf.close();
InputStream instm = new FileInputStream(new File("source.txt"));
OutputStream outstm = new FileOutputStream(new File("destination.txt"));
byte[] buf = new byte[1024];
int siz;
while ((siz = instm.read(buf)) > 0) {
outstm.write(buf, 0, siz);
}
instm.close();
outstm.close();
BufferedReader br = new BufferedReader(
new FileReader("destination.txt"));
String str;
while ((str = br.readLine()) != null) {
System.out.println(str);
}
instm.close();
}

}

Output :

The above will produce by the above code after execution :

This string is copied from one file to another                                                                                    

Download Source Code

Advertisement

Related Tags for Copy one file into another:


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: February 17, 2011

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com