import java.io.*; import java.util.Scanner; /** Reading with a Scanner @author P. Conrad (adapted it for CS56 and added comments) @see also http://www.javapractices.com/topic/TopicAction.do?Id=42 */ public class ReadFromFile2 { public static void main(String [] args) { if (args.length != 1) { System.err.println("Usage: java ReadFromFile2 filename"); System.exit(1); } int lineNumber = 0; Scanner scanner = null; /* try { */ // The next line is typical of stuff you'll see in Java. // Each nested constructor adds some "layer"---and // each thing inside represents one of several "choices". scanner = new Scanner(new FileReader(new File(args[0]))); // Use a Scanner to get each line while ( scanner.hasNextLine() ){ String thisLine = scanner.nextLine(); lineNumber ++; System.out.printf("[%04d] %s\n",lineNumber,thisLine); } /* } catch (Exception e) { System.out.println("Ooops, an exception! " + e); // e.printStackTrace(); } finally { scanner.close(); } // try/catch/finally */ } // main }