加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 输入stream.read返回0或-1?

发布时间:2020-12-14 05:35:32 所属栏目:Java 来源:网络整理
导读:有什么区别 byte[] buffer = new byte[1024];// this:if (inputStream.read(buffer) 0) { /*...*/ }// and:if (inputStream.read(buffer) != -1) { /*...*/ } 两者都能确定网络流终止吗? 解决方法 InputStream.read() 的Javadocs说: If the length of b is
有什么区别
byte[] buffer = new byte[1024];
// this:
if (inputStream.read(buffer) > 0) { /*...*/ }
// and:
if (inputStream.read(buffer) != -1) { /*...*/ }

两者都能确定网络流终止吗?

解决方法

InputStream.read()的Javadocs说:

If the length of b is zero,then no bytes are read and 0 is returned

在正常使用中,这种情况永远不会发生,因此明确地测试这种情况并没有多大意义. (如果你想避免永远循环,因为在这种情况下缓冲区是零长度和快速失败,只需测试缓冲区的长度.)

还有,有:

Returns: the total number of bytes read into the buffer,or -1 if there is no more data because the end of the stream has been reached.

如果要测试文件结束(或网络流,或其他),请使用测试:

if ( inputStream.read(buffer) != -1 ) ...

非bug的Java实现永远不会返回任何其他内容,以表明没有更多的数据可用.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读