Java Detect Closed Stream

Derek picture Derek · Apr 10, 2011 · Viewed 7.5k times · Source

I have a general socket implementation consisting of an OutputStream and an InputStream.

After I do some work, I am closing the OutputStream.

When this is done, my InputStream's read() method returns -1 for an infinite amount of time, instead of throwing an exception like I had anticipated.

I am now unsure of the safest route to take, so I have a few of questions:

  • Am I safe to assume that -1 is only returned when the stream is closed?
  • Is there no way to recreate the IO exception that occurs when the connection is forcefully broken?
  • Should I send a packet that will tell my InputStream that it should close instead of the previous two methods?

Thanks!

Answer

WhiteFang34 picture WhiteFang34 · Apr 10, 2011

The -1 is the expected behavior at the end of a stream. See InputStream.read():

Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.

You should still catch IOException for unexpected events of course.