/* * T03n04.java -- Using BufferedReader to read lines of a text file. * This is how you had to do it before the release of Java 1.5. * Be sure to run T03n02.java before attempting to run this program. * * It's hard not to notice the clutter caused by the three sets of * try/catch blocks. We could put all three sections of code in one * try/catch pair, but that doesn't allow us to tailor the error message. * We could compress this a bit by putting the common catch code into a * static method. * * We use a priming read on the input loop, because it's possible that * the input file is empty. If so, the first read will get nothing, * and we don't want to print a null String. * * Why do we need BufferedReader in addition to FileReader? * It is entirely possible to read the file w/o a BufferedReader object, but * buffering the input stream is usually more efficient. (Why? Take a * class on OS design to find out!) */ import java.io.*; public class T03n04 { public static void main (String [] args) { final String fileName = "T03n02.out"; File fileRef; FileReader fileStream; BufferedReader textStream = null; String aLine = null; System.out.println("Reading some text from the file '" + fileName + "'..."); try { fileRef = new File(fileName); fileStream = new FileReader(fileRef); // Throws the exception textStream = new BufferedReader(fileStream); } catch (FileNotFoundException e) { System.out.println("I/O ERROR: Your requested file does not" + "seem to exist.\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("-----------------------------------------"); try { aLine = textStream.readLine(); while (aLine != null) { System.out.println(aLine); aLine = textStream.readLine(); } } catch (IOException e) { System.out.println("I/O ERROR: Something went wrong with the " + "reading 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("-----------------------------------------"); try { textStream.close(); } catch (IOException e) { System.out.println("I/O ERROR: Something went wrong with the " + "closing of the text stream.\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("Done!"); } }