1   // joi/9/copy/Copy2.java                         
2   //                                                            
3   //                                                            
4   // Copyright 2003 Bill Campbell and Ethan Bolker                         
5                                                               
6   import java.io.*;
7   
8   /**
9    * Simple read-a-line write-a-line loop to exercise file I/O.
10   *
11   * Usage: java Copy2 inputfile outputfile
12   */
13  
14  public class Copy2 
15  {
16      /**
17       * All work is done here.
18       *
19       * @param args names of the input file and output file.
20       */
21  
22      public static void main( String[] args ) 
23      {
24          BufferedReader inStream  = null;
25          BufferedWriter outStream = null;
26          String line;
27  
28          try {
29              // open the files
30              inStream =  new BufferedReader(new FileReader(args[0]));
31              outStream = new BufferedWriter(new FileWriter(args[1]));
32  
33              // copy
34              while ((line = inStream.readLine()) != null) {
35                  outStream.write( line );
36                  outStream.newLine();
37              }
38          }
39          catch (IndexOutOfBoundsException e) {
40              System.err.println(
41                  "usage: java Copy2 sourcefile targetfile" );
42          }
43          catch (FileNotFoundException e) {
44              System.err.println( e );  // rely on e's toString()
45          }
46          catch (IOException e) {
47              System.err.println( e );
48          }
49          finally { // close the files
50              try {
51                  if (inStream != null) {
52                      inStream.close();
53                  }
54              }
55              catch (Exception e) {
56                  System.err.println("Unable to close input stream.");
57              }
58              try {
59                  if (outStream != null) {
60                      outStream.close();
61                  }
62              }
63              catch (Exception e) {
64                  System.err.println("Unable to close output stream.");
65              }
66          }
67      }
68  }
69