tags:

views:

72

answers:

3

In our project sometimes when we use InputStream.read(byte[] b) method, there is some error.
When we use

byte[] b = new byte[1024];
int len = -1;
while ((len = io.read(b, 0, 1024)) != -1) {
    response.getOutputStream().write(b, 0, len);
}

then it goes well.

I found the source code, which is amazing

public int read(byte b[]) throws IOException {
    return read(b, 0, b.length);
}

Inside read method, it calls read(b, 0, b.length). In our project, b.length equals 1024, so why do we get the error?

Does anybody know the difference between these two methods? Thanks

+1  A: 

Seeing as read(byte[]) calls read(byte[], int, int), there is no difference. The first is just a shorter way of doing the read. There must obviously be something else that is wrong, such as wrong input parameters or something of the like.

EDIT: Like Zenzen said, what error do you get?

gablin
A: 

The most likely reason for your error is that there are not 1024 bytes available to read from the InputStream. Notice that from your example

read(b, 0, b.length);

is safely checking the number of bytes available to read from the stream, where as the static 1024 byte read you referenced

read(b, 0, 1024)

is not taking this precaution.

Ashley Walton
I think you misunderstood. The code failed when they tried using the `read(byte[])` method, but worked when they replaced that to directly use the `read(byte[], int, int)` method.
gablin
A: 

As indicated, an exception and stack trace would be very helpful.

Read can return a length of zero. Is it possible that your OutputStream does not support writes of length 0 ? The JavaDocs for OutputStream don't indicate a restriction, but it seems possible that a subclass could have such a boundary error.

Jim Rush