import java.io.*; import java.util.Scanner; /** Reading with a Scanner This version uses the try/catch block @author P. Conrad (adapted it for CS56 and added comments) @see also http://www.javapractices.com/topic/TopicAction.do?Id=42 */ public class ReadFromFile4 { public static void main(String [] args) throws FileNotFoundException { if (args.length != 1) { System.err.println("Usage: java ReadFromFile4 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 (FileNotFoundException fnfe) { } catch (IllegalArgumentException iae) { System.out.println("Ooops, I was unable to find the file " + args[0]); // e.printStackTrace(); // return; } finally { System.out.println("Inside the finally block"); if (scanner!=null) {scanner.close();} } // try/catch/finally System.out.println("Outside the entire try/catch/finally"); } // main }