Copying Text based Files in Java

Waqas Anwar
08 April 2008
4744 Views

Java IO Package provides two streams we can use to read and write all types of files including images, audio, video or even text files. These classes are FileInputStream and FileOutputStream. In the following tutorial, I will show you how you can use these classes to read and write image file.

import java.io.*;

public class FileCopier
{
      public static void main(String[] args)
      {
            String readFile = "C:\\myfile.txt";
            String writeFile = "C:\\myfile1.txt";
            try
            {
                  FileInputStream fin = new FileInputStream(readFile);
                  FileOutputStream fout = new FileOutputStream(writeFile);
                  int i;       
                  while(  ( i = fin.read() )  != -1  )
                  {
                        fout.write(i);
                  }
       
                  fin.close();
                  fout.close();
                  System.out.println("File Copied Successfully");
            }
            catch(IOException ex)
            {
                  System.out.println("IO Error");
            }                
      }
}