开发者

java inputstream

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

The d开发者_StackOverflow社区ocumentation doesn't specify the behavior.


..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.


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)


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜