import java.io.*; /** * Project #5.3 * CS 2334, Section 001 * Sept 23, 2002 *
* This classs implements a program that shows how Exceptions work. *
* @author unknown * @version 1.0 */ public class FileDisplay3 { /** * This is the main method for this test program. Since this is a * simple test program, all of our code will be in the main method. * Typically this would be a bad design, but we are just testing out * some features of Java. *
* Algorithm
* 1. Read the command line arguments for a file name, if no filename
* is given, then ask for one.
* 2. Display the file to the screen.
*
* @return The filename input by the user */ public static String inputFilename() throws IOException { String fileName = "-1"; // Print a friendly message requesting a filename. System.out.print("Please enter a file name: "); // Use a BufferedReader to get user input. InputStreamReader isr = new InputStreamReader(System.in); BufferedReader userReader = new BufferedReader(isr); // Read a line of text from the user. try { fileName = userReader.readLine(); } catch(IOException ioe) { System.out.println("Cannot read from BufferedReader"); System.exit(1); } return fileName; } /** * Displays the contents of the given file to the screen. *
* @param fileName The name of the file to display. * @throws IOException Thrown if there is an error displaying the file. */ public static void displayFile(String fileName) throws IOException { String line; // Open the file for reading. BufferedReader buffReader = openFile(fileName); // Read in each line and display it. while((line = buffReader.readLine()) != null) { System.out.println(line); }// null signifies End-of-File. buffReader.close(); } /** * Opens the file and creates a BufferedReader for it. *
* @param fileName The file to be opened. * @return A BufferedReader to read from the specified file * @throws IOException Thrown if there is an error opening the file */ public static BufferedReader openFile(String fileName) throws IOException { // Open the file using a FileReader. FileReader fileReader = new FileReader(fileName); BufferedReader buffReader = new BufferedReader(fileReader); return buffReader; } } // End class FileDisplay3