java输入流
当到达流末尾时,InputStream
的 available()
方法应该返回什么?
文档没有指定行为。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
当到达流末尾时,InputStream
的 available()
方法应该返回什么?
文档没有指定行为。
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(5)
不要使用
available()
来检测流结束!相反,请查看InputStream.read()
,其中:Don't use
available()
for detecting end of stream! Instead look to theint
returned byInputStream.read()
, which:JavaDoc 确实在“返回”部分告诉您 -
(来自 InputStream JavaDoc)
The JavaDoc does tell you in the Returns section -
(from InputStream JavaDoc)
理论上,如果到达流末尾,则没有字节可供读取,并且 available 返回 0。但要小心。并非所有流都提供此方法的真正实现。 InputStream 本身总是返回 0。
如果您需要非阻塞功能,即从流中读取而不在读取时被阻塞,请改用 NIO。
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.
来自 Java 7 文档:
“在到达输入流末尾时可以无阻塞地读取(或跳过)此输入流的字节数的估计值或 0。”
所以,我想说在这种情况下它应该返回 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.
返回可以从此输入流读取(或跳过)的字节数的估计值,而不会被该输入流的方法的下一次调用所阻塞。下一次调用可能是同一个线程或另一个线程。单次读取或跳过这么多字节不会阻塞,但可能会读取或跳过更少的字节。
http://download.oracle .com/javase/6/docs/api/java/io/InputStream.html#available%28%29
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.
http://download.oracle.com/javase/6/docs/api/java/io/InputStream.html#available%28%29