Difference between read(byte[] b, int off, int len) and read(byte [] b)
In our project sometimes when we us开发者_开发百科e InputStream.read(byte[] b)
method, there is some error.
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
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?
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.
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.
精彩评论