Copy one file to another in java

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

 

Copyfile.java

 

import   java.io.*;

import java.util.*;

class  Copyfile

{

public static  void  main(String arg[]) throws  Exception

{

Scanner sc=new Scanner(System.in);

System.out.print("Provide source file name :");

String sfile=sc.next();

System.out.print("Provide destination file name :");

String dfile=sc.next();

FileReader  fin = new   FileReader(sfile);

FileWriter fout=new FileWriter(dfile,true);

int c;

while((c=fin.read()) != -1)

{

fout.write(c);

}

System.out.println("Copy finish...");

fin.close();

fout.close();

}

}

 

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 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.

 

 

 

Ebook Download
View all
Learn
View all