Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
374 views
in Technique[技术] by (71.8m points)

java.util.scanner - Is it safe not to close a Java Scanner, provided I close the underlying readable?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...