简体   繁体   中英

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.

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. And I am sure that the client sends the whole 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! 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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