Now we try to copy file in Java. We can do that by copy contents from one file to another file. Sounds difficult huh? Not really. First, we need import package.

Then we creates a new File instance for the file name passed as parameter, and creates another InputStream instance for the input object and OutputStream instance for the output object passed as parameter.

And then create byte type buffer for buffering the contents of one file, and write to another specified file. Hm.. thats is the recipe of ‘Copy File in Java’.

Here the example code:


public class CopyFile{
	public static void main(String[] args){
			File f1 = new File(args[0]);
			File f2 = new File(args[1]);
			InputStream in = new FileInputStream(f1);
			OutputStream out = new FileOutputStream(f2);

			byte[] buf = new byte[1024];
			int len;
			while ((len = > 0){
				out.write(buf, 0, len);
			System.out.println("File copied.");
		}catch(IOException e){
copy file example

copy file example

Now, you try:mrgreen: