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
- Prompt the user for a Source file and a Destination file.
- Open a
FileReaderconnected to the Source. - Open a
FileWriterconnected to the Destination. - Use a
whileloop to read one character from the Source:c = fread.read(). - Immediately write that character to the Destination:
fwrite.write(c). - Close both streams in the
finallyblock.
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
BufferedReaderandBufferedWriterwould make the copying process significantly faster.
Complexity
Time Complexity
O(n)
Space Complexity
O(1)