Copy File To Another File In Java Example
Chapter:
File
Last Updated:
20-06-2016 17:06:02 UTC
Program:
/* ............... START ............... */
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class JavaCopyFileToAnotherFile {
public static void main(String[] args) {
FileInputStream instream = null;
FileOutputStream outstream = null;
try {
File infile = new File("C:\\MyInputFile.txt");
File outfile = new File("C:\\MyOutputFile.txt");
instream = new FileInputStream(infile);
outstream = new FileOutputStream(outfile);
byte[] buffer = new byte[1024];
int length;
while ((length = instream.read(buffer)) > 0) {
outstream.write(buffer, 0, length);
}
instream.close();
outstream.close();
System.out.println("File copied successfully!!");
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
/* ............... END ............... */
Output
File copied successfully!!
Notes:
-
Java Program first read the file using FileInputStream and then write the read content to the output file using FileOutputStream.
Tags
Copy File To Another File, Java, I/O