Closing Reader/Stream in Java [duplicate]

2019-09-11 08:24发布

问题:

This question already has an answer here:

  • How can I fix an “IOException: Stream closed” exception using System.in? 1 answer

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.