File Copy Tutorial Java


File Copy Tutorial Java

Using finally block to close streams

For real time programming, the above program is modified where file handles are closed in finally block. finally block statements are guaranteed of execution even if the exceptions thrown by different constructors and methods are not handled successfully. It is the best practice.

import java.io.*;
public class FileToFile1
{
  public static void main(String args[])
  {
    FileInputStream fis = null;        
    FileOutputStream fos = null;        
    try
    {
      fis = new FileInputStream("pqr.txt");
      fos = new FileOutputStream("xyz.txt");

      int k;
      while( ( k = fis.read() ) != -1 )
      {
        fos.write(k);  
        System.out.print((char) k);  
      }
     } 
     catch(FileNotFoundException e)
     {
       System.out.println("File does not exist. " + e);
     }
     catch(IOException e)
     {
       System.out.println("Some I/O problem. " + e);
     }
     finally
     {
       try
       {
         if(fos != null)
           fos.close();
         if(fis != null)
           fis.close();
       }
       catch(IOException e)
       {
       	 System.out.println("File is not closed properly. " + e);
       } 
     }
   }
}
       if(fos != null)
          fos.close();

The above statement is another good programming practice, to check whether FileOutputStream object is created or not (closing when not created raises exception). It is done by comparing fos with null.

Learn performance tips in file copying

2 thoughts on “File Copy Tutorial Java”

Leave a Comment

Your email address will not be published.