How to Copy a File in Java


In this example we will show the method to copy a file to another file in Java.

Source Code

package com.beginner.examples;

import java.io.*;

public class FileOperator14Example { 
	public static void main(String[] args )
    {	
		try
        {
             int length = 0; 
             File file = new File("example.txt"); 
             if (file.exists())
             {
               InputStream in = new FileInputStream(file); 
               FileOutputStream out = new FileOutputStream("copy.txt"); 
               byte[] buffer = new byte[1024];
               while ( (length = in.read(buffer)) != -1) 
               { 
                 out.write(buffer, 0, length); 
               } 
               in.close();
               out.close();
               System.out.println("Done!");
             }
        } 
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

Output:

Done!
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments