Reputation: 3
I’m trying to understand Try-with-resource. After reading few articles, I understand that each class who implement or extend closable/auto-closable 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 Closable
, instead I have the classic method close()
, seems to be a wrap of Closable
.
My question, who should implement or extend Closable
, is it the source of data, like files for FileInputStream
class and Readable interface for the Scanner
class.
Thanks you !
Upvotes: 0
Views: 2646
Reputation: 1920
Both of your classes implements Closeable
which extends AutoCloseable
.
Reading their javadoc helps but, in the end, their close
method will be automatically called by the try-with-resources.
An object that may hold resources (such as file or socket handles) until it is closed. The
close()
method of anAutoCloseable
object is called automatically when exiting atry
-with-resources block for which the object has been declared in the resource specification header. This construction ensures prompt release, avoiding resource exhaustion exceptions and errors that may otherwise occur.
Upvotes: 3
Reputation: 11120
FileInputStream
extends InputeStream
InputStream
and Scanner
both implement Closable
Closable
extends AutoClosable
So FileInputStream
and Scanner
instances are AutoClosable
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.
Upvotes: 0