Java Reference
In-Depth Information
needed. If a stream is not explicitly closed it will hold on to these re-
sources. A stream class could define a
finalize
method to release these
resources during garbage collection but, as you learned on page
449
,
that could be too late. You should usually close streams when you are
done with them.
[1]
Yes, another misspelling
All byte streams also share common synchronization policies and con-
current behavior. These are discussed in
Section 20.5.1
on page
515
.
20.2.1.
InputStream
The abstract class
InputStream
declares methods to read bytes from
a particular source.
InputStream
is the superclass of most byte input
streams in
java.io
, and has the following methods:
public abstract int
read()
tHRows IOException
Reads a single byte of data and returns the byte that was
read, as an integer in the range 0 to 255, not 128 to 127; in
other words, the byte value is treated as unsigned. If no byte
is available because the end of the stream has been reached,
the value 1 is returned. This method blocks until input is avail-
able, the end of stream is found, or an exception is thrown.
The
read
method returns an
int
instead of an actual
byte
value
because it needs to return all valid byte values plus a flag
value to indicate the end of stream. This requires more values
than can fit in a
byte
and so the larger
int
is used.
public int
read(byte[] buf, int offset, int count)
tHRows IOException
Reads into a part of a
byte
array. The maximum number of
bytes read is
count
. The bytes are stored from
buf[offset]
up
to a maximum of
buf[offset+count-1]
all other values in
buf
are left unchanged. The number of bytes actually read is re-