Next: None. Up: Files. Previous: The FileInputStream class.


Case study: Copying a file

Let's look at a program that illustrates these three classes at work. This program copies one file into another location. You would invoke it via the command line; for example, if you wanted to copy the file ``CopyFile.java'' into a file named ``CopyFile.bak'', you would type the following at the Unix prompt.

% java CopyFile CopyFile.java CopyFile.bak
  1  import java.io.*;
    
  2  public class CopyFile {
  3      public static void main(String[] args) {
  4          if(args.length != 2) {
  5              System.out.println("usage: java CopyFile source dest");
  6              return;
  7          }
    
  8          File src_f = new File(args[0]);
  9          File dst_f = new File(args[1]);
 10          if(!src_f.exists() || !src_f.canRead()) {
 11              System.out.println("cannot find source: " + src_f.getName());
 12              return;
 13          } else if(dst_f.exists()) {
 14              System.out.println("destination file " + dst_f.getName()
 15                  + " already exists");
 16              return;
 17          }
    
 18          try {
 19              FileInputStream src = new FileInputStream(src_f);
 20              FileOutputStream dst = new FileOutputStream(dst_f);
 21              byte[] buffer = new byte[512];
    
 22              while(true) {
 23                  int count = src.read(buffer);
 24                  if(count == -1) break;
 25                  dst.write(buffer, 0, count);
 26              }
    
 27              src.close();
 28              dst.close();
 29          } catch(IOException e) {
 30              System.out.println("Error during copy: " + e.getMessage());
 31              if(dst_f.exists()) dst_f.delete();
 32          }
 33      }
 34  }

One non-obvious thing about this program is the try block: We know the FileInputStream and FileOutputStream constructor methods throw a FileNotFoundException, and yet the only exception we catch is an IOException object. The reason we could get away with this is that FileNotFoundException is a subclass of IOException, so that, if the constructor invoked in line 19 throws a FileNotFoundException, the catch clause of line 29 would still catch it, since the exception is also an IOException.


Next: None. Up: Files. Previous: The FileInputStream class.