Home‎ > ‎Applied Core Java‎ > ‎Basic I/O‎ > ‎

Copy a Text File

Problem : How you can make copy of a text file?

Solution :
java.io.FileReader  will be used to read data from source text file and java.io.FileWriter will be used to write data to target text file.

Program :

Step 1 - Coding

Create a text file c:sunilos/CopyFile.java and copy below contents.

import java.io.FileReader;
import java.io.FileWriter;

import com.sun.corba.se.impl.ior.WireObjectKeyTemplate;

 * A program to copy from one file to another file.
public class CopyFile {

    public static void main(String[] args) throws Exception{
        String source = "c:/sunilos/sunilos.txt";
        String target = "c:/sunilos/sunilos-copy.txt";

        //File writer takes chars and convert into bytes and write to a file
        FileReader reader = new FileReader(source);

                 // PrintWriter takes lines and convert that into charters and gives to FileWriter 
        FileWriter writer = new FileWriter(target);
        int ch = reader.read();
            ch= reader.read();
        System.out.println(source + " is copied to " + target);


Step 2 - Deployment

  1. Create a folder 'c:\sunilos'. 
  2. Create or copy CopyFile.java  into 'c:\sunilos' folder.
  3. It is assumed that your hard drive has c:/sunilos/sunilos.txt file.
  4. Open your command prompt and go to  'c:\sunilos'
  5. Compile CopyFile.java with help of 
    • javac CopyFile.java command.  Command will create CopyFile.class file in 'c:/sunilos/com/sunilos/io/' folder.
  6. Congratulations!! your Java program is ready to serve.

Step 3 - Testing

  1. Make sure you are on Command Prompt under c:\sunilos directory
  2. Now start your java program from command prompt with help of 
    • java CopyFile command.
  3. Now to check your data open
    • c:/sunilos/sunilos-copy.txt


C:\sunilos>java -cp . com.sunilos.io.CopyFile
c:/sunilos/sunilos.txt is copied to c:/sunilos/sunilos-copy.txt

<<Previous | Next>>
Mahima Hardia,
Aug 19, 2011, 10:57 PM