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 = null; // fileReader must be initialized
                                   // outside the try block
        try {
            fileReader = new Scanner(new File(fileName));
            while ( fileReader.hasNextLine() ) {
                System.out.println(fileReader.nextLine());
            }   
        }
        catch(FileNotFoundException ex) {
            System.out.println("Error -- File " +fileName+ " not found.");
            echoFile(); // recursion is most elegant but an explicit
                        // loop could also be used
        }
    }
}

previous | index | next