Copy File Content to Another Using Java

In this article, you will learn how to copy a file content to another file. In general, copying files’ content to another file is something that programmers often do for many reasons, such as creating a backup or just having a temporary placeholder for the content.

How to copy a file content to another file using Java?

Below is the code for copying the content of a source file into a destination file. Please note that this code requires the java.io namespace to be imported.

import java.io.*;
public class Main {

  public static void main(String args[]) {
    try {
      File sourceFile = new File("C:/File.txt");

      FileInputStream fileInputStream = new FileInputStream(sourceFile);

      int fileLength = (int) sourceFile.length();

      byte Bytes[] = new byte[fileLength];

      FileOutputStream fileOutputStream = new FileOutputStream("C:/File-Copy.txt");

      for (int i = 0; i < fileLength; i++) {
        fileOutputStream.write(Bytes[i]);
      }

      System.out.println("File has been copied Successfully!");

      fileInputStream.close();
      fileOutputStream.close();
    } catch (Exception e) {
      System.out.println(e);
    }
  }

}

Output

If both files exist, the output is:

File has been copied Successfully!

If one of the files does not exist, or something went wrong during the executing of this program, an error message will be thrown.

Happy Coding!

Leave a Reply

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