Copying Text based Files in Java


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");
            }                 
      }
}

 

 

About author


User avatar

Waqas Anwar

Founder of EzzyLearning.com, Senior Consultant, Microsoft .NET and Web Technologies

Comments