Java Reference
In-Depth Information
int bytesAvailable = in . available ();
byte [] input = new byte [ bytesAvailable ];
int bytesRead = in . read ( input , 0 , bytesAvailable );
// continue with rest of program immediately...
In this case, you can expect that bytesRead is exactly equal to bytesAvailable . You
cannot, however, expect that bytesRead is greater than zero. It is possible that no bytes
were available. On end of stream, available() returns 0. Generally, read(byte[] in
put, int offset, int length) returns -1 on end of stream; but if length is 0, then
it does not notice the end of stream and returns 0 instead.
On rare occasions, you may want to skip over data without reading it. The skip()
method accomplishes this task. It's less useful on network connections than when read‐
ing from files. Network connections are sequential and normally quite slow, so it's not
significantly more time consuming to read data than to skip over it. Files are random
access so that skipping can be implemented simply by repositioning a file pointer rather
than processing each byte to be skipped.
As with output streams, once your program has finished with an input stream, it should
close it by invoking its close() method. This releases any resources associated with the
stream, such as file handles or ports. Once an input stream has been closed, further
reads from it throw IOException s. However, some kinds of streams may still allow you
to do things with the object. For instance, you generally won't retrieve the message digest
from a java.security.DigestInputStream until after the data has been read and the
stream closed.
Marking and Resetting
The InputStream class also has three less commonly used methods that allow programs
to back up and reread data they've already read. These are:
public void mark ( int readAheadLimit )
public void reset () throws IOException
public boolean markSupported ()
In order to reread data, mark the current position in the stream with the mark() method.
At a later point, you can reset the stream to the marked position using the reset()
method. Subsequent reads then return data starting from the marked position. However,
you may not be able to reset as far back as you like. The number of bytes you can read
from the mark and still reset is determined by the readAheadLimit argument to
mark() . If you try to reset too far back, an IOException is thrown. Furthermore, there
can be only one mark in a stream at any given time. Marking a second location erases
the first mark.
Marking and resetting are usually implemented by storing every byte read from the
marked position on in an internal buffer. However, not all input streams support this.
Search WWH ::




Custom Search