Copy one file to another in java

By Satyapriya Nayak Sep 23, 2011
In this blog we will know how to copy one file to another file in java.
Download Files: java.rar

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.

 

 

 

Satyapriya Nayak

Satyapriya Nayak is a software developer from Bhubaneswar, India. He holds a Bachelor's degree in Electronics and telecommunication and is an active member of C# Corner. 

COMMENT USING

PREMIUM SPONSORS

Hire Mobile & Web Developer on demand. 100% satisfaction. Try for 1 week or Money Back. Local and remote developers available all over USA.

Latest Blogs