benplumley
benplumley

Reputation: 87

If I reinstantiate a Scanner, does the old one close?

I have this code:

Scanner fileReader = new Scanner(myFile);
// some code
fileReader = new Scanner(myFile);
// some more code
fileReader.close();

It does what I want it to (starts the reader again from the top of the file) but have I left a Scanner open by instantiating twice and only closing once? Should I have closed before I reinstantiated? What I have works, but I'd like to know whether it's good practice or not.

Upvotes: 2

Views: 114

Answers (1)

Stephen C
Stephen C

Reputation: 719739

If I reinstantiate a Scanner, does the old one close?

Nope.

Should I have closed before I reinstantiated?

Yup.

What I have works, but I'd like to know whether it's good practice or not.

It is bad practice. It is a resource leak. If you do that too much, you are likely to find that new Scanner(myFile) will throw an exception, complaining that it has run out of file descriptors (or something like that).

The recommended practice is to use the try with resources syntax to ensure that the scanner gets closed no matter what. (Or if you are "old school" and / or stuck on Java 6 or earlier ... close the scanner in a finally block ... carefully.)

Example:

   try (Scanner fileReader = new Scanner(myFile)) {
      // some code
   }
   try (Scanner fileReader = new Scanner(anotherFile)) {
      // some more code
   }

It is not necessary to explicitly close either fileReader. Each try has an implicit finally block that calls close on all of the Closeable resources like the Scanner objects we created there.)

Upvotes: 6

Related Questions