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

前端之家收集整理的这篇文章主要介绍了java – 输入stream.read返回0或-1?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有什么区别
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

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

还有,有:

@H_403_22@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实现永远不会返回任何其他内容,以表明没有更多的数据可用.

原文链接:https://www.f2er.com/java/122050.html

猜你在找的Java相关文章