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

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

还有,有:

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

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...