繁体   English   中英

从InputStream读取到byte []会引发IndexOutOfBoundsException

[英]Reading from InputStream to byte[] throws IndexOutOfBoundsException

我显然不知道问题出在哪里!,首先,我请客户端向我发送他要发送的byte[]的长度,然后我这样读取它的长度。

int i = 323292; // length of incoming Byte[]
byte[] b = new byte[i]; 
int readBytes=inputStream.read(b,0,b.length);

但是它总是读取的readBytes小于i。 而且我确定客户端会发送整个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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM