Introduction

In this blog, we will know how to copy one file to another file in java.

Copyfile.java

  1. import java.io.*;
  2. import java.util.*;
  3. class Copyfile {
  4. public static void main(String arg[]) throws Exception {
  5. Scanner sc = new Scanner(System.in);
  6. System.out.print("Provide source file name :");
  7. String sfile = sc.next();
  8. System.out.print("Provide destination file name :");
  9. String dfile = sc.next();
  10. FileReader fin = new FileReader(sfile);
  11. FileWriter fout = new FileWriter(dfile, true);
  12. int c;
  13. while ((c = fin.read()) != -1) {
  14. fout.write(c);
  15. }
  16. System.out.println("Copy finish...");
  17. fin.close();
  18. fout.close();
  19. }
  20. }

Compile

Make a directory java in any drive (E:\java). Store two text files one containing data and one empty and java file(Copyfile.java) into that directory.
Open the command prompt and go to that directory for compiling the java file as
E:\Documents and Settings\Administrator>cd\
E:\>cd E:\java
E:\java>javac Copyfile.java
E:\java>java Copyfile
Provide source file name :x.txt
Provide destination file name :y.txt
Copy finish…
You will notice all data present in x.txt file are copied to y.txt file.