[英]Reading from InputStream to byte[] throws IndexOutOfBoundsException
I obviously don't know where is the problem!, First I ask the client to send me the Length of the byte[]
he is going to send, then I read for its length like this. 我显然不知道问题出在哪里!,首先,我请客户端向我发送他要发送的
byte[]
的长度,然后我这样读取它的长度。
int i = 323292; // length of incoming Byte[]
byte[] b = new byte[i];
int readBytes=inputStream.read(b,0,b.length);
But It always kept reading readBytes less than i. 但是它总是读取的readBytes小于i。 And I am sure that the client sends the whole
byte[]
. 而且我确定客户端会发送整个
byte[]
。
I tried to put it inside a loop, to read till my total number of read bytes is i, but I always get IndexOutOfBoundsException after the second Iteration! 我试图将其放入循环中,直到我的总读取字节数为i为止,但是在第二次迭代后,我始终会得到IndexOutOfBoundsException! here is the code
这是代码
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;
}
}
AnyIdeas? 有任何想法吗?
This: 这个:
read = inputStreamFromClient.read(b, threshold, b.length);
should be: 应该:
read = inputStreamFromClient.read(b, threshold, b.length - threshold);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.