Is it safe not to close a Java Scanner, provided I close the underlying readable?

Anthony picture Anthony · May 7, 2011 · Viewed 40.8k times · Source

If I have a method that takes a reader and I want to operate on the reader with a Scanner like so:

Scanner scanner = new Scanner(reader);
while(scanner.hasNext()) {
    //blah blah blah
}

Is it safe not to close scanner? Documentation says that it "closes this scanner" and then talks about closing the underlying readable. Suppose I don't want to close the readable and instead want the caller to close reader when ready. Is it safe not to close scanner here?

Answer

Stephen C picture Stephen C · May 7, 2011

It depends what you want to be safe against.

  • If you are just trying to ensure that the underlying stream is closed, then either approach is fine.

  • If you also want the Scanner to be marked as closed (so that all subsequent operations on the object will fail immediately), then you should call Scanner.close().

This is a general principle; i.e. it also applies to various kinds of streams that do in-memory buffering, one way or another.