Search code examples
javatry-catch-finallyprintstream

Closing Scanner/PrintStream in finally-block which are declared in try-block


I am trying to close a Scanner and a PrintStream in a finally-block, which are declared in a try-block. The problem is, if the try-block fails because of an exception, the Scanner and Printstream are never declared, resulting in an error in the finally-block, where I want to close them. Here's the code:

        try {
            File readFile = new File(readFileName);
            File writeFile = new File(writeFileName);
            Scanner fileScanner = new Scanner(readFile);
            PrintStream output = new PrintStream(new FileOutputStream(writeFile,false)); // overwrite
            while(fileScanner.hasNextLine()) {
                output.println(fileScanner.nextLine());
                if (!fileScanner.hasNextLine()) {
                    break;
                }
                output.println();
            }
        }
        
        catch (FileNotFoundException fnfe) {
            System.out.println(fnfe.getMessage());
            System.exit(0);
        }
        
        finally {
            fileScanner.close();
            output.close();
        }

EDIT: Thank you for the answers, I solved it without try-with-resources by declaring the Scanner and Printstream before the try-block and then initialising them in the try-block, like this:

Scanner fileScanner = null;
PrintStream output = null;
        try {
            fileScanner = new Scanner(readFile);
            output = new PrintStream(new FileOutputStream(writeFile,false));
            ...
        }

Solution

  • You may use try-with-resources construction:

    File readFile = new File(readFileName);
    File writeFile = new File(writeFileName);
    
    try (Scanner fileScanner = new Scanner(readFile); PrintStream output = new PrintStream(new FileOutputStream(writeFile,false))) {
    
        while(fileScanner.hasNextLine()) {
            output.println(fileScanner.nextLine());
            if (!fileScanner.hasNextLine()) {
                break;
            }
            output.println();
        }
    
    } catch (FileNotFoundException fnfe) {
        System.out.println(fnfe.getMessage());
        System.exit(0);
    }        
    

    Since both Scanner and PrintStream implement Autocloseable interface, they will be closed automatically on exception or after execution of try block