/********************************************************************************
 Author:           Jim Skrentny, skrentny@cs.wisc.edu
                   copyright 1999, all rights reserved
 Revisions by:     Deb Deppeler, deppeler@cs.wisc.edu (2005)
                   Eric Lantz, lantz@cs.wisc.edu (2005)
 Version:          1.5
 Compiler:         Eclipse 3.0 (JDK 1.5)
 Platform:         Windows 2000
 *******************************************************************************/

import java.io.*;                       // for java file I/O
import java.util.StringTokenizer;       // to divide line into pieces
import java.util.Scanner;               // to use the Scanner class of 1.5

/**
 * This program demonstrates how to do file input and output in Java using
 * character streams and text files.  Java file I/O can be complicated to
 * understand, but you can get started by following and copying the code
 * examples below.
 *
 * BUGS: none known
 */
public class FileIO {

    private static Scanner scanner;  // console input
    private static Scanner inFile;   // file input

    // The "throws IOException" clause is required in methods having java
    // file I/O or any methods that directly or indirectly call others having
    // file I/O.  Later in class you'll learn that this isn't required if the
    // method catches IOExceptions.  
    public static void main (String[] args) throws IOException {
    
        // This program uses console I/O.  Please see the ConsoleIO.java example
        // program before looking at this one.
        
        System.out.println("Example program demonstrating:\nFILE IO\n");
        System.out.println("BEFORE PROCEEDING: create a file with these 2 lines:");
        System.out.println("Dolphin|1999|");
        System.out.println("Lion|2000|");
        System.out.println("\nUse this file's path for the source file path.");
        
        // Create the Scanner object for console input.
        scanner = new Scanner( System.in );
            
        // Java file input and output begins with the actual file stored in the
        // computer's file system.  These files are the source or destination of
        // the characters that are process by a program.  We'll access files by
        // first creating a File object that is associated with the path where
        // the actual file is located in the computer's file system.
        
        // The code example shown uses two File objects, one for the source and
        // another for the destination.  The path for the actual file is entered
        // by the program user for both the source and destination files.  See
        // Ch. 16 for more information about paths and file systems.
        
        File srcFile, dstFile;  // declare the object variables

        // First the user enters the path of the source file, which must be a
        // valid file for the loop to end.
        boolean repeat = false; // assume a valid path is entered on first try
        
        do {
            System.out.print("Enter the path of the source file: ");
            srcFile = new File(scanner.nextLine());  // create File object
            
            // check if source file doesn't exist
            if (!srcFile.exists()) {
                System.out.println("ERROR: file not found");
                repeat = true;
            }
            // check if source file isn't a file or isn't readable
            else if (!srcFile.isFile() || !srcFile.canRead()) {
                System.out.println("ERROR: file not readable");
                repeat = true;
            }
            else
                repeat = false;
                
        } while (repeat);
        
        // Second the user enters the path of the destination file, which must
        // be a valid file for the loop to end.
        repeat = false; // assume a valid path is entered on the first try
        
        do {
            System.out.print("Enter the path of the destination file: ");
            dstFile = new File(scanner.nextLine());  // create the File object
            
            // if destination file already exists check if it is a directory
            // or isn't writeable
            if (dstFile.exists()
            && (dstFile.isDirectory() || !dstFile.canWrite())) {
                System.out.println("ERROR: file not writeable");
                repeat = true;
            }
            else
                repeat = false;
                
        } while (repeat);

        // At this point source and destination File objects are associated with
        // actual files in the computer's file system.  Next objects are created
        // that enable the program to read from or write to the files in a
        // convenient manner.
        
        // Reading from a file is done in a manner similar to reading from the
        // console, that is, a Scanner is created.  Instead of System.in, the source
        // of file input is a File object. 
        // This is how it is coded:
        
        inFile = new Scanner( srcFile );

        // Writing to a file is done in a manner similar to writing to the
        // console.  A PrintWriter object is created, which also uses a File object.
        // PrintWriter allows us to use the same print and println methods that
        // we used in console output. 
        // This is how it is coded:
        
        PrintWriter outFile = new PrintWriter( dstFile );
            
        // The inFile and outFile objects can now be used to do file I/O.  The
        // following code illustrates some methods that are used to read from
        // and write to files.
        
        // The hasNext method is used to determine if there are more characters
        // in the file. It returns true if there are more characters in the
        // file, false when the end of the file is reached.
        while (inFile.hasNext()) {
        
            // nextLine method reads an entire line (same as console input)
            String line = inFile.nextLine();
            
            // Often a line of characters must be divided into parts (i.e.
            // tokens), which are then converted (i.e. parsed) into the
            // appropriate data types.  Tokenizing a line is done using a
            // StringTokenizer.  StringTokenizer objects are constructed
            // from the string to be divided and a string of delimiters.
            // Delimiters are the points where the line should be broken.
            // In this example the string that is read is divided at pipe
            // characters, i.e. "|".
            StringTokenizer tokenizer = new StringTokenizer(line, "|");
            
            // If you've created the two line file as instructed above, the
            // first token on a line is a string.  We can get tokens from the
            // StringTokenizer using the nextToken method.  This method returns
            // a String object of the next group of characters upto but not
            // including the next delimiter. Other methods include countTokens
            // that returns the number of tokens left in the StringTokenizer,
            // and hasMoreTokens that returns true if there are more tokens
            // remaining in the StringTokenizer.
            String name = tokenizer.nextToken();
            
            // Notice the same technique as with console input is used to parse
            // (i.e.convert) the next token into an integer value. Other
            // techniques described in the ConsoleIO.java file can be used to
            // convert to other types of data.
            int year = Integer.parseInt(tokenizer.nextToken());
            
            // We'll display this line on the console:
            System.out.println("Name: " + name + ", Year: " + year);
            
            // and also save it in the output file.  PrintWriter objects can do
            // println and print methods that work the same as for System.out.
            outFile.println(name + "|" + year + "|");
        }
        
        // Finally, always close your files before finishing to guarantee that
        // buffered data isn't lost.
        inFile.close();
        outFile.close();
                
        // This is how you can read from a file using a Scanner object and 
        // write to a file using a PrintWriter.  By copying the code examples
        // above, you can use file input and output in your programs.
    }
    
}
