previous | index | next

Exception Handling: I/O Errors

The class below prompts the user for a file name and then echoes the file to standard output:
public class FileEchoer {
    public static void main(String[] args) {
        echoFile();
    }
    private static void echoFile() {
        Scanner fileNameReader = new Scanner(System.in);
        System.out.println("Enter a file name: ");
        String fileName = fileNameReader.nextLine();
        Scanner fileReader = new Scanner(new File(fileName));
        while ( fileReader.hasNextLine() ) {
            System.out.println(fileReader.nextLine());
        }       
    }
}
However, as it stands the class will not compile, because a possible FileNotFoundException is not handled.

Rewrite the echoFile method so that if the file is not found the message "Error -- File fileName not found." is printed to the screen and the user is prompted again.


previous | index | next