Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to copy content of one file to another File .

Java Code Example — File Handling Programs

ADVERTISEMENT

Java Program to copy content of one file to another File .

Objective

Write a Java program to copy the contents of one file to another.

Algorithm / Approach

  1. Prompt the user for a Source file and a Destination file.
  2. Open a FileReader connected to the Source.
  3. Open a FileWriter connected to the Destination.
  4. Use a while loop to read one character from the Source: c = fread.read().
  5. Immediately write that character to the Destination: fwrite.write(c).
  6. Close both streams in the finally block.
CopyFile.java
import java.io.*;
import java.util.*;
class CopyFile {
 public static void main(String[] a)
 {
  FileReader fread = null;
  FileWriter fwrite = null;
  Scanner s=new Scanner(System.in);
  System.out.print("Enter Source: ");
  String src = s.nextLine();
  System.out.print("Enter Dest.: ");
  String des = s.nextLine();
  try {
   fread = new FileReader(src);
   fwrite = new FileWriter(des);
   int c = fread.read();
   while(c != -1) {
    fwrite.write(c);
    c  = fread.read();
   }
   System.out.println("File Copied");
  }
  catch(Exception e) {
   System.out.print(e);
  }
  finally {
   try {
    fread.close();
    fwrite.close();
   }
   catch(Exception e) {
    System.out.print(e);
   }
  }
 }
}

Expected Output

Enter Source: Alok.txt
Enter Dest.: Dan.txt
File Copied

Explanation of the Program

  • This program elegantly combines reading and writing into a single pipeline.
  • As characters are sucked out of the source file, they are immediately piped into the destination file. Because this happens character by character, it is very memory efficient—you could copy a 10GB file without running out of RAM.
  • For production code, wrapping these in BufferedReader and BufferedWriter would make the copying process significantly faster.

Complexity

Time Complexity O(n)
Space Complexity O(1)
ADVERTISEMENT