java

Try-with-resource / Closeable-AutoCloseable


I’m trying to understand Try-with-resource. After reading few articles, I understand that each class who implements or extends Closeable/AutoCloseable can benefit from the close() method which is called to close the object.

Now in practice I have this code:

try (FileInputStream inputStream = new FileInputStream(instructionFile);
     Scanner sc = new Scanner(inputStream, "UTF-8")) {
    while (sc.hasNextLine()) {
        String startingPosition = sc.nextLine();
        String instructions = sc.nextLine();
        // Some actions
    }
    if (sc.ioException() != null) {
        throw sc.ioException();
    }
} catch (NoSuchElementException e) {
    throw new IncompleteInstructions();
} catch (IOException e) {
    throw e;
}

As you can see, I used FileInputStream and Scanner classes, I was expecting to see both of those class implements or extends Closeable, instead I have the classic method close(), seems to be a wrap of Closeable.

My question, who should implement or extend Closeable, is it the source of data, like files for FileInputStream class and Readable interface for the Scanner class.

Thank you !


Solution

  • FileInputStream extends InputStream

    InputStream and Scanner both implement Closeable

    Closeable extends AutoCloseable

    So FileInputStream and Scanner instances are AutoCloseable and after the instructions in the try block finish the execution, JVM will automatically call .close() method on those resources. As Java docs state,

    The try-with-resources statement ensures that each resource is closed at the end of the statement.