Is it necessary to close Scanner when there is no stream underlying?

烂漫一生 提交于 2021-02-07 12:24:16

问题


Directly from this Scanner API:

String input = "1 fish 2 fish red fish blue fish";
     Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
     System.out.println(s.nextInt());
     System.out.println(s.nextInt());
     System.out.println(s.next());
     System.out.println(s.next());
     s.close(); 

回答1:


First we make our habits; then our habits make us.

I'd say close the stream, because ingraining a habit like closing resources in finally blocks make sense.




回答2:


I don't think so, but it's best to close it anyway in case you change your code to use a stream. It's also a good habit, one that you really want to get into.




回答3:


There will be no resource leak if we dont close Scanner of String. Internally new Scanner(String) creates a StringReader as underlying source, when we close Scanner it closes StringReader which makes no effect.




回答4:


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




回答5:


I believe it is a good idea of using scanner.close(); I say this this because it will prevent resource leaks and if you make this into a habit then it will be very beneficial to you.




回答6:


Even though a scanner is not a stream, you need to close it to indicate that you're done with its underlying stream [1]. IDEs like Eclipse will often issue a warning that you have a "Resource leak: 'scanner' is never closed".

Note: don't close a Scanner that's tied to System.in! Since the System.in object is opened by the JVM, you should leave it to the JVM to close it [2].



来源:https://stackoverflow.com/questions/17945683/is-it-necessary-to-close-scanner-when-there-is-no-stream-underlying

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!