THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

All byte streams have some things in common. For example, all streams support the notion of being open or
closed. You open a stream when you create it, and can read or write while it is open. You close a stream with
its close method, defined in the Closeable[1] interface. Closing a stream releases resources (such as file
descriptors) that the stream may have used and that should be reclaimed as soon as they are no longer needed.
If a stream is not explicitly closed it will hold on to these resources. 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 concurrent 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 intread()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 available,
the end of stream is found, or an exception is thrown. The read method
Free download pdf