Close a Scanner linked to System.in

I have a Scanner linked to System.in . Now, after using the Scanner , I should close it, as it is bad coding practice to leave it open. But, if I close the Scanner , I will also be closing System.in ! Can anyone tell me how I can close the Scanner without closing System.in (if there is any way).


One option is to wrap your System.in stream in a CloseShieldInputStream that prevents it from being closed. Your reader would then use the CloseShieldInputStream rather than the raw System.in stream.

Here is the API for the class: http://commons.apache.org/io/apidocs/org/apache/commons/io/input/CloseShieldInputStream.html


The simplest thing is to not close Scanner if you don't want to close the underlying stream.

Ideally you should create just one Scanner which you use for the life of the program. In any case, it appears you don't have a good reason to close it.


Instead of adding shield classes and stuff like that, just put a nice comment and a

        @SuppressWarnings("resource")

That's good enough. And I don't seem to see a lot of drawbacks to this approach. Don't forget the comment.

链接地址: http://www.djcxy.com/p/96098.html

上一篇: NoSuchElement特殊程序中的异常错误

下一篇: 关闭与System.in链接的扫描仪