Copying Text based Files in Java

You are currently viewing 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. We can copy a file from one location to another using FileInputStream and FileOutputStream classes. The main logic of copying file is to read the contents of the file associated with FileInputStream and write the same contents into the file associated with FileOutputStream. In the following tutorial, I will show you how you can use these classes to read and write a simple text 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");
            }                 
      }
}

READ ALSO:  Singleton Design Pattern in Java

Leave a Reply