Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Java scanner implement Closeable?

I asked this question yesterday. I think I got the right answer, but one of the other answers left me with a question. If I have code like this:

File file = new File("somefile.txt");
try (Scanner in = new Scanner(file)) {
    //do something but don't explicitly call file.close()
}

Is this wrong? From what I understand the try-with-resources statement will close a resource if that resource implements Closeable or AutoCloseable. In my mind I equate this to using the with statement to open file resources in Python. But the answer from @David Newcomb says that Scanner is not Closeable.

I looked at the Java source and I found the line:

public final class Scanner implements Iterator<String>, Closeable {

That means to me that I am safe using try-with-resources and that the file resource will be closed at the end of the try block without explicitly calling file.close(). Am I right or should I be doing something differently?

like image 939
noel Avatar asked Dec 03 '25 18:12

noel


1 Answers

So now we have no doubts that try-with-resources will call Scanner.close(). Now lets see Scanner.close API:

If this scanner has not yet been closed then if its underlying readable also implements the Closeable interface then the readable's close method will be invoked.

Since Scanner was created with File argument, it will create FileInputStream internally and will close it automatically. File object does not need closing since its not a Closeable resource.

like image 117
Evgeniy Dorofeev Avatar answered Dec 06 '25 08:12

Evgeniy Dorofeev