2

What is an InputStream's available() method is supposed to return when the end of the stream is reached?

The documentation doesn't specify the behavior.

1
  • 1
    Well, the documentation does say that this method should be overriden by subclasses so the behaviour depends on the implementation and can probably be different for different types of streams. Commented Sep 23, 2011 at 10:00

5 Answers 5

2

..end of the stream is reached

Don't use available() for detecting end of stream! Instead look to the int returned by InputStream.read(), which:

If no byte is available because the end of the stream has been reached, the value -1 is returned.

Sign up to request clarification or add additional context in comments.

Comments

1

The JavaDoc does tell you in the Returns section -

an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking or 0 when it reaches the end of the input stream. 

(from InputStream JavaDoc)

1 Comment

My bad. Doesn't it prevent non-blocking IO use?
1

Theoretically if end of stream is reached there are not bytes to read and available returns 0. But be careful with it. Not all streams provide real implementation of this method. InputStream itself always returns 0.

If you need non-blocking functionality, i.e. reading from stream without being blocked on read use NIO instead.

Comments

0

From the Java 7 documentation:
"an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking or 0 when it reaches the end of the input stream."

So, I would say it should return 0 in this case. That also seems the most intuitive behaviour to me.

Comments

0

Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream. The next invocation might be the same thread or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes.

The available method for class InputStream always returns 0. 

http://download.oracle.com/javase/6/docs/api/java/io/InputStream.html#available%28%29

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.