我显然不知道问题出在哪里!,首先我要求客户端向我发送他要发送的byte[]
的长度,然后我读取它的长度,例如这个。
int i = 323292; // length of incoming Byte[]
byte[] b = new byte[i];
int readBytes=inputStream.read(b,0,b.length);
但是它总是读取小于i的readBytes。我确信客户端发送了整个 byte[]
。
我试图将它放在一个循环中,读取直到我的读取字节总数为 i,但在第二次迭代后我总是得到 IndexOutOfBoundsException!这是代码
boolean flag = true;
int i = 323292;
int threshold = 0;
byte[] b = new byte[i];
int read = 0;
while (flag) {
if (threshold < i) {
System.out.println(threshold);
try {
read = inputStreamFromClient.read(b, threshold, b.length);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
threshold = threshold + read;
} else {
flag = false;
}
}
有什么想法吗?
最佳答案
这个:
read = inputStreamFromClient.read(b, threshold, b.length);
应该是:
read = inputStreamFromClient.read(b, threshold, b.length - threshold);
关于java - 从 InputStream 读取到 byte[] 会抛出 IndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10559292/