编辑:对于一般流,您只需继续阅读,直到您基本上阅读了您想要阅读的所有内容。对于DataInput
(例如DataInputStream
)的实现,您应该使用readFully
Peter Lawrey 所建议的。考虑这个答案的其余部分与您只有一个InputStream
.
任何类型的数据给你的数据都比你要求的少,这是完全合理的InputStream
,即使有更多的数据在路上。您应该始终针对这种可能性进行编码——除了ByteArrayInputStream
. (当然,如果剩下的数据比您要求的少,那么返回的数据仍然可能少于请求的数据。)
这是我正在谈论的那种循环:
byte[] data = new byte[messageSize];
int totalRead = 0;
while (totalRead < messageSize) {
int bytesRead = stream.read(data, totalRead, messageSize - totalRead);
if (bytesRead < 0) {
// Change behaviour if this isn't an error condition
throw new IOException("Data stream ended prematurely");
}
totalRead += bytesRead;
}