import java.io.*; /** * Project #5.1 * CS 2334, Section 001 * Sept 23, 2002 *

* This classs implements a program that shows how exceptions work. *

* @author unknown * @version 1.0 */ public class FileDisplay { /** * 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. *

* @param args Contains the command line arguments. */ public static void main(String args[]) throws IOException { String fileName; /* 1. Read the command line arguments for a file name, if no filename * is given, then ask for one. */ if (args.length == 0) { System.out.println("This program displays a file specified by" + " a command line argument."); System.out.println("You didn't specify a filename," + " so please enter one now.\n"); fileName = inputFilename(); } else { fileName = args[0]; } // 2. Display the file to the screen. displayFile(fileName); } /** * Queries the user for a file name. *

* @return The filename input by the user */ public static String inputFilename() throws IOException { // 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. String fileName = userReader.readLine(); 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 { // Open the file for reading. BufferedReader buffReader = openFile(fileName); // Read in each line and display it. String line; 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); // Wrap the FileReader with a BufferedReader for ease of use. BufferedReader buffReader = new BufferedReader(fileReader); return buffReader; } } // End class FileDisplay