/* * T03n03.java -- The Scanner class provides a pair of line-of-text * methods that makes the task of reading lines almost trivial. * Be sure to run T03n02.java first, to create the input file used by * this program. * * Note that we need a File object. Scanner does have a constructor * that takes a String object, but it doesn't use that as a file name; * rather, you can scan that string as if it were an input file. That's * nice, but it means you can't directly open a file using just Scanner. * * See the next example to see how to read from a text file using * pre-1.5 Java classes. */ import java.io.*; import java.util.*; public class T03n03 { public static void main (String [] args) { final String fileName = "T03n02.out"; File aFile; Scanner inFile = null; // Need to initialize to please Java String aLine; System.out.println("Reading some text from the file '" + fileName + "'..."); aFile = new File(fileName); try { inFile = new Scanner(aFile); } catch (IOException e) { System.out.println("I/O ERROR: Something went wrong with the " + "opening of the text file.\nHere's what " + "I can tell you:"); System.out.println(" The Error: " + e.getClass().getName()); String mesg = e.getMessage(); if (mesg == null) { System.out.println("The message: None."); } else { System.out.println("The message: " + mesg); } System.out.println("The stack trace:"); e.printStackTrace(); } System.out.println("-----------------------------------------"); while (inFile.hasNextLine()) { // Scanner handles lines with ease aLine = inFile.nextLine(); System.out.println(aLine); } System.out.println("-----------------------------------------"); } }