Page 609 - Introduction to Programming with Java: A Problem Solving Approach
P. 609

                14.10 MultiplecatchBlocks 575
 /****************************************************************
*
PrintLineFromFile2.java
Dean & Dean
This opens an existing text file and prints a line from it.
****************************************************************/
*
*
*
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
public class PrintLineFromFile2
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
String fileName;
// name of target file
BufferedReader fileIn; // target file
String line;
// first line from fileIn
System.out.print("Enter a filename: ");
fileName = sAtpdIan.gneoxtLiPneD()F; Enhancer try
{
fileIn = new BufferedReader(new FileReader(fileName));
line = fileIn.readLine();
System.out.println("Line 1:\n" + line);
} // end try
  Sequence of catch blocks
    catch (FileNotFoundException e)
{
}
{
}
System.out.println("Error reading from file: " + fileName);
System.out.println("Invalid filename: " + fileName);
catch (IOException e)
     }
// end PrintLineFromFile2 class
}
// end main
Sample session with input of an invalid filename:
 Enter a filename: garbage
Invalid filename: garbage
Figure 14.13 PrintLineFromFile2 program—an improved file-reader


















































   607   608   609   610   611