从InputStream读取到byte []会抛出IndexOutOfBoundsException

时间:2012-05-11 22:14:32

标签: java sockets networking inputstream

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

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

但是它总是比我读读读数少。我相信客户端会发送整个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;
    }
}

AnyIdeas?

1 个答案:

答案 0 :(得分:7)

此:

read = inputStreamFromClient.read(b, threshold, b.length);

应该是:

read = inputStreamFromClient.read(b, threshold, b.length - threshold);