Program to Copy Files in Java

Exercise:

Write a Java Program to copy file.

Click Here to View the Solution!
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
  
 public class Main {
   public static void main(String[] args) {
  
     byte[] array = new byte[50];
     try {
       FileInputStream sourceFile = new FileInputStream("input.txt");
       FileOutputStream destFile = new FileOutputStream("newFile");
  
       sourceFile.read(array);
       destFile.write(array);
       System.out.println("The input.txt file is copied to newFile.");
  
       // closes the stream
       sourceFile.close();
       destFile.close();
     }
     catch (Exception e) {
       e.getStackTrace();
     }
   }
 } 
Click Here to View the Output!
The input.txt file is copied to newFile.
Click Here to View the Explanation!
  • In this program, one file has been copied to another file with the help of FileInputStream and FileOutputStream.
  • All the data of input.txt which is to be copied is read from the FileInputStream and stored in an array.
  • This data is then read from the array and written to the newFile through the FileOutputStream.
  • The method copyFile() which copies the contents of a file, is utilized in this program by exporting org.apache.commons.io package, FileUtils class in it to be specific.
  • Another method copy() which too copies a file’s content, is utilized in this program by exporting java.nio package, Files class in it to be specific.