• Post Reply Bookmark Topic Watch Topic
  • New Topic

Stream Closed Problem  RSS feed

 
Yaki Kumar
Greenhorn
Posts: 12
Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello!

The problem is I want to close the stream where I read the message - in "getInput(int type)" method. But closing the stream as below - or even in the finally block - gives me a Stream Closed exception. I cannot understand why am I getting this error , after all I am creating a new Stream and a new Reader in the method and closing it should be no problem, as new ones would be available the next time method is called. Removing is.close() and br.close() from code - line number 41 and 42 lets the program run the way I want.





What do I need to do in order to read the response, close the streams, and yet be able to call the method several times as above.

Thank You in advance.
Vikesh
 
Rob Spoor
Sheriff
Posts: 21050
85
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should never close System.in, System.out or System.err. At the moment, you are closing System.in. Simply remove the is.close() and br.close() statements.
 
Yaki Kumar
Greenhorn
Posts: 12
Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Rob,

One silly question - Even if I remove is.close() while not removing br.close() gives the same error. Does it so happen that br.close() closes my InputStreamReader here. Do I need to know something more?

Also, since System.in, System.out and System.err should not be closed, so it makes no sense in creating InputStreamReader object in some method as I have done to use it again and again - does it?. But I can close them when exiting the application/program - should I?

Thanks again.
Vikesh
 
Rob Spoor
Sheriff
Posts: 21050
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Most, if not all, input streams, output streams, readers and writers will close any underlying input stream, output stream, reader or writer. So when you call br.close(), this will close is, which in turn closes System.in. And that's something that you don't want.

To be able to use a BufferedReader for reading from System.in you will need to convert System.in into a Reader, and that's what the InputStreamReader will do. The only thing you could possibly change is create only one InputStreamReader / BufferedReader pair, store them (as instance fields), and use them throughout the program. And because these two will remain wrapped around System.in you will not have to close them at all.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!