Close a Scanner linked to System.in

烈酒焚心 提交于 2019-11-25 22:33:58

问题


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).


回答1:


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




回答2:


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.




回答3:


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.




回答4:


I have vague memories of strange, undiagnosable problems long ago with using the same Scanner of System.in twice, so this is what I use (even though you should probably just use one scanner for the duration of the program):

static String input() {
    try {
        return new Scanner(System.in).nextLine();
    } catch (NoSuchElementException e) {
        throw e;
    }
}

For some reason this works without warnings, whereas if I don't do the catch-throw, Eclipse will complain Resource leak: '<unassigned Closeable value>' is never closed.




回答5:


According to the API for InputSteam "The close method of InputStream does nothing.", so since System.in is an instance of InputStream, you don't need to worry about close() being called on it.



来源:https://stackoverflow.com/questions/14142853/close-a-scanner-linked-to-system-in

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