How to close scanner object when it is called outside of the enclosing class?

531 views java
1

Let's say I have a custom reader object that throws exception:

public StationReader {

    public StationReader(String inFile) throws FileNotFoundException {
        Scanner scan = new Scanner(inFile);

        while (scan.hasNextLine() {
            // blah blah blah
        }

        // Finish scanning
        scan.close();       
    }
}

And I call the StationReader in another class, Tester:

public Tester {

    public static void main(String[] args) {

        try {
            StationReader sReader = new StationReader("i_hate_csv.csv");

        } catch (FileNotFoundException e) {
            System.out.println("File not found arggghhhhhh");
        } finally {
            // HOW TO CLOSE SCANNER HERE??
        }
    }
}

Now let's imagine that whilst scanning through the lines, an exception is thrown, so scan.close() is never called.

How do I close the scanner object then in this case?

answered question

Use a try-with-resources or make the StationReader Closable

1 Answer

2

Write the read process in a try-with-resources statement, but don't catch any of the exceptions, simply let them be passed back to the caller, for example...

public class CustomReader {

    public CustomReader(String inFile) throws FileNotFoundException {
        try (Scanner scan = new Scanner(inFile)) {
            while (scan.hasNextLine()) {
                // blah blah blah
            }
        }
    }
}

The try-with-resource statement will automatically close the resource when the code exists the try block

fyi: finally use to be used for this, but when you have multiple resources, it become messy. All hail try-with-resources ????

posted this

Have an answer?

JD

Please login first before posting an answer.