// File Example
// Chris Wilcox
// wilcox
// 10/15/2012
// CS160

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.Scanner;

public class FileExample {

    public static void main(String[] args) {

        int count = 0;
        
        try {

            // Open input stream
            Scanner scan = new Scanner(new File(args[0]));

            // Read contents
            while (scan.hasNextLine()) {
                
                // Read line
                String line = scan.nextLine();
                
                // Print line
                System.out.println(count + " " + line);
                count++;
            }
                
            // Close input stream
            scan.close();

        } catch (IOException e) {
            System.out.println("Cannot read file: " + args[0]);
            System.exit(0);
        }


        // Open output file
        try {
            
            // Open output stream
            PrintWriter output = new PrintWriter(new File(args[1]));

            // Formatter class
            DecimalFormat fmt = new DecimalFormat("0.00");

            output.println("Real number: " + fmt.format(123456.789));
            output.println("Integer number: " + 987654);
            output.println("String variable: " + "Hello There");

            // Close output stream
            output.close();

        } catch (IOException e) {
            System.out.println("Cannot write file: " + args[1]);
            System.exit(0);
        }
    }
}

© 2012 CS160 Colorado State University. All Rights Reserved.