Java Reference
In-Depth Information
byte [] input = new byte [ 1024 ];
int bytesRead = in . read ( input );
It attempts to read 1,024 bytes from the InputStream in into the array input . However,
if only 512 bytes are available, that's all that will be read, and bytesRead will be set to
512. To guarantee that all the bytes you want are actually read, place the read in a loop
that reads repeatedly until the array is filled. For example:
int bytesRead = 0 ;
int bytesToRead = 1024 ;
byte [] input = new byte [ bytesToRead ];
while ( bytesRead < bytesToRead ) {
bytesRead += in . read ( input , bytesRead , bytesToRead - bytesRead );
}
This technique is especially crucial for network streams. Chances are that if a file is
available at all, all the bytes of a file are also available. However, because networks move
much more slowly than CPUs, it is very easy for a program to empty a network buffer
before all the data has arrived. In fact, if one of these two methods tries to read from a
temporarily empty but open network buffer, it will generally return 0, indicating that
no data is available but the stream is not yet closed. This is often preferable to the
behavior of the single-byte read() method, which blocks the running thread in the same
circumstances.
All three read() methods return -1 to signal the end of the stream. If the stream ends
while there's still data that hasn't been read, the multibyte read() methods return the
data until the buffer has been emptied. The next call to any of the read() methods will
return -1. The -1 is never placed in the array. The array only contains actual data. The
previous code fragment had a bug because it didn't consider the possibility that all 1,024
bytes might never arrive (as opposed to not being immediately available). Fixing that
bug requires testing the return value of read() before adding it to bytesRead . For ex‐
ample:
int bytesRead = 0 ;
int bytesToRead = 1024 ;
byte [] input = new byte [ bytesToRead ];
while ( bytesRead < bytesToRead ) {
int result = in . read ( input , bytesRead , bytesToRead - bytesRead );
if ( result == - 1 ) break ; // end of stream
bytesRead += result ;
}
If you do not want to wait until all the bytes you need are immediately available, you
can use the available() method to determine how many bytes can be read without
blocking. This returns the minimum number of bytes you can read. You may in fact be
able to read more, but you will be able to read at least as many bytes as available()
suggests. For example:
Search WWH ::




Custom Search