user5035229
user5035229

Reputation: 23

Do I have to close FileInputStream if I close Scanner

I have read this question: Do I have to close FileInputStream?

What if I use a Scanner like this https://www.baeldung.com/java-scanner and close the Scanner? Does the scanner.close() close the FileInputStream as well?

Upvotes: 2

Views: 585

Answers (1)

Adrian Russo
Adrian Russo

Reputation: 556

Yes it will. Consider the following code:

FileInputStream inputStream = new FileInputStream("file.txt");
Scanner scanner = new Scanner(inputStream);
scanner.close();
System.out.println(inputStream.read());

This throws a java.io.IOException because the stream is closed.

Edit: Or, as said by Slaw, check the documentation.

Upvotes: 4

Related Questions