当InputStream.read(array)不返回array.length时到达流的结尾?

时间:2014-04-07 18:58:41

标签: java sockets byte bytearray inputstream

我有这些代码:

final int packetLength = 64 //just some constant
InputStream in = socket.getInputStream();
byte[] packet = new byte[packetLength];
int read = in.read(packet, 0, packetLength)

if(read != packetLength) {
    //End of stream=
}

我可以确定如果read(byte[], int, int)没有返回与它应该读取的长度相同的值,那么流已经到达流的末尾了吗?

因为下一个read()来电应该返回-1不应该吗?

1 个答案:

答案 0 :(得分:3)

不,你不能确定。 InputStream在读取您请求的所有数据之前不会阻塞 - 它会阻塞,直到它读取某些数据为止。 (InputStream 的默认实现将读取,直到它读取所有内容,但不能保证子类实现会这样做。)

您应该阅读,直到read调用返回-1 - 或者您只想准确读取packetLength个字节:

byte[] packet = new byte[packetLength];
int offset = 0;
while (offset < packetLength) {
    int bytesRead = in.read(packet, offset, packetLength - offset);
    if (bytesRead == -1) { 
        // Incomplete packet - handle however you want to
    }
    offset += bytesRead;
}
// Hooray - read the complete packet.