Ahmed Emad
Ahmed Emad

Reputation: 629

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?

Upvotes: 2

Views: 2440

Answers (1)

MByD
MByD

Reputation: 137312

This:

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

should be:

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

Upvotes: 7

Related Questions