Closing Reader/Stream in Java [duplicate]

笑着哭i 提交于 2020-01-17 04:32:09

问题


In my code I have to read user input from console:

class Demo {
    //...some code
    public String readUserInput() throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String userInput = reader.readLine();
        reader.close();
        return userInput;
    }
}

On first time when I use method readUserInput() on Demo object everything is OK. But when I create another Demo object and call method - it throws Exception with the message

"Stream closed"

Can anybody tell me, why I have Exception on different not equal objects? Thank you for your attention.


回答1:


The problem is here:

new InputStreamReader(System.in)

When you close your BufferedReader, it closes the InputStreamReader, which in turn closes System.in.

This is all (kind of) explained in the contract of Closeable's .close(), which says:

Closes this stream and releases any system resources associated with it.

As a result, the second time you try and read from your BufferedReader, this ultimately results in data being read from System.in, but it is unavailable. Hence your error.


More generally, you handle your resources poorly. Please read about, and learn to use, the try-with-resources statement.




回答2:


You are closing the reader, which close... System.in

In this case, you don't have to close the Stream.



来源:https://stackoverflow.com/questions/33304629/closing-reader-stream-in-java

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