java

How to copy a file in Java

In this tutorial, we are going to see how to copy a file in Java. To copy a file, simply convert the file to a byte stream with FileInputStream and write the bytes to another file with FileOutputStream.
 

How to copy a file in Java

Here is an example to copy a file named “src.txt” to another file named “dest.txt”. If the “dest.txt” file exists, the existing content will be overwritten.
 

import java.io.*;

public class Main {
	
  public static void main(String args[]) {
    
    File src = new File("C:\\Users\\PC\\Desktop\\src.txt"); 
    File dest = new File("C:\\Users\\PC\\Desktop\\dest.txt"); 
    InputStream is = null;
    OutputStream os = null;
	
    try {
        is = new FileInputStream(src);
        os = new FileOutputStream(dest);
        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer)) > 0) {
            os.write(buffer, 0, len);
        }
        is.close();
        os.close();
    }
    catch(IOException e){
        e.printStackTrace();
    }
  }
}
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *