//  File:  FileCopy.java

//  Show how to use the Scanner class to read one line at a time
//  Show how to create a PrintWriter to simplify output

import java.util.*;
import java.io.*;

class FileCopy {

    public static void main(String[] args) {
        if (args.length != 2) {
            System.out.println("Usage:  java FileCopy SourceFile TargetFile");
            System.exit(0);
        }

        copy(args[0], args[1]);
    }

    /*
     *  copy is declared static because it is entirely self-contained.
     *  copy can be ported to any context. It only needs util.* and io.*
     */
    public static void copy(String source, String target) {
        PrintWriter pw = null;
        Scanner     sc = null;

        try {
            // Create a scanner for reading the SourceFile
            sc = new Scanner(new File(source));

            // Create a printwriter for writing the TargetFile
            pw = new PrintWriter(
                     new BufferedWriter(
                         new FileWriter(target)));

            // Loop: Read a line; Write a line; until no more lines...
            while (true)
                pw.println(sc.nextLine());

        } catch (FileNotFoundException e) {
            System.err.println("ERROR: " + e + "\n");

        // This is the NORMAL EXIT for the while loop
        } catch (NoSuchElementException e) {
            // do nothing; the finally clause will close the file
            System.out.println("YEAH! Out of data at this point");
    
        } catch (IOException e) {
            System.err.println("ERROR: " + e + "\n");

        } finally {
            if (sc != null)
                sc.close();        // Close the Scanner
            if (pw != null)
                pw.close();        // Close the PrintWriter file
        }    
    } // end copy method

} // end class FileCopy
