import java.util.Scanner; import java.io.*; /** * CS151 Fall 2007 Lab 11 Solution.
* Class for practicing file reading and writing. Uses United Nations data on cinema attendance by * country to demonstrate some potential issues when reading data files. * * @author Scott Russell * @version created 11/13/2007, last modified 11/14/2007 */ public class UNDataReader { /** * Conversion factor for computing data expressed in millions to the corresponding integer. */ public static final double MILLION = 1000000; // since FileNotFoundException is a subclass of IOException we need only specify the superclass public static void main(String[] args) throws IOException { // Link a Scanner to the terminal window to get file name input from the user Scanner console = new Scanner(System.in); // Solicit a filename from the user System.out.print("Please enter the name of the file to read from: "); String inputFileName = console.next(); // create a reader for that file and then a Scanner using that reader FileReader reader = new FileReader(inputFileName); Scanner input = new Scanner(reader); // Solicit a filename from the user using same console Scanner System.out.print("Please enter the name of the file to write to: "); String outputFileName = console.next(); // Open a file for writing PrintWriter writer = new PrintWriter(outputFileName); // display some header information in the terminal window but not in the output file System.out.println("Country, Attendance (millions)"); /* start reading the file * keep reading and discarding lines until the first line that starts with an integer * that hopefully represents a Country Code is found */ while (input.hasNextLine() && !input.hasNextInt()) { // read and discard the entire line input.nextLine(); } // continue to read records as long as there's another line that starts with an integer while (input.hasNextLine() && input.hasNextInt()) { // read and discard the country code input.nextInt(); // For each record, start with an empty String for the countryName and keep appending to it // the next word found until that is a double String countryName = new String(); while (!input.hasNextDouble()) countryName += input.next() + " "; // remove the trailing space countryName = countryName.trim(); // read the attendance and multiply by a million to convert to actual integer double attendance = input.nextDouble() * MILLION; // discard the remainder of the line if any input.nextLine(); // print out to the screen and file the information System.out.println(countryName + "," + (int) attendance); writer.println(countryName + "," + (int) attendance); } // close both the reader and the writer reader.close(); writer.close(); } }