/** * FileScanner.java * * @author Jeff Ondich * @version 2/18/10 * * Illustrates the use of Scanner and File to read through * a file one line at a time, parsing each line as we go. * * We assume that the text file specified as the single * command-line argument consists of lines like this: * * Susan 1968 * Bob 1945 * Esme 2003 * * etc. That is, a line plus a year. */ import java.util.*; import java.io.*; public class FileScanner { public static void main(String[] args) throws IOException { if( args.length != 1 ) { System.out.println("Usage: java FileScanner filetoscan"); System.exit(1); } // Read the file one line at a time using fileScanner. String fileName = args[0]; Scanner fileScanner = new Scanner(new File(fileName)); while( fileScanner.hasNextLine() ) { String line = fileScanner.nextLine(); // For each line, extract the name and the year-of-birth. Scanner lineScanner = new Scanner(line); String name = ""; if( lineScanner.hasNext() ) name = lineScanner.next(); int yearOfBirth = 0; if( lineScanner.hasNextInt() ) yearOfBirth = lineScanner.nextInt(); int age = 2009 - yearOfBirth; // Not a very robust program! System.out.println(name + " is " + age + " years old, more or less."); } } }