0

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.

maxshuty
  • 9,708
  • 13
  • 64
  • 77
thrashzone
  • 33
  • 7
  • When you `close()` the `BufferedReader` it delegates that closing to the contained `InputStreamReader` which in turn delegates closing to the contained `InputStream`, which is `System.in` in this case, and your application only has one `System.in`. You close it, you're done. – JimmyB Oct 23 '15 at 14:22

2 Answers2

4

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.

fge
  • 119,121
  • 33
  • 254
  • 329
  • Oh, I didn't know, that after closing Reader, System.in will be closed too. Thank you. – thrashzone Oct 23 '15 at 14:25
  • Yeah, the javadoc isn't really clear about it; and `System.in` being a one shot resource for the entire life of a program is quite tricky to handle... – fge Oct 23 '15 at 14:26
0

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

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

fluminis
  • 3,575
  • 4
  • 34
  • 47