Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Scanner with string input should be closed?

Sonar complains that the Scanner should always be closed, is it right?

Scanner scanner = new Scanner("simple string")

This scanner is not scanning from file etc. Why should it be closed?

like image 350
user9449907 Avatar asked Aug 01 '26 17:08

user9449907


1 Answers

By calling new Scanner("string") it creates a StringReader which creates a character stream. So you have to close it.

See the OpenJDK source code

public Scanner(String source) {
    this(new StringReader(source), WHITESPACE_PATTERN);
}
like image 155
Murat Karagöz Avatar answered Aug 04 '26 07:08

Murat Karagöz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!