}
The idea behind IOException is this: streams are mostly used to exchanging data with devices
that are outside the JVM. If something goes wrong with the device, the device needs a universal
way to indicate an error to the client code.
Consider, for example, a printer that refuses to print a document because it is out of paper. The
printer needs to signal an exception, and the exception should be relayed to the user; the
program making the print request has no way of refilling the paper tray without human
intervention. Moreover, this exception should be relayed to the user immediately.
Most stream exceptions are similar to this example. That is, they often require some sort of user
action (or at least user notification), and are often best handled immediately. Therefore, the
designers of the streams library decided to make IOException a checked exception, thereby
forcing programs to explicitly handle the possibility of failure.
Some foreshadowing: RMI follows a similar design
philosophy. Remote methods must be declared to throw
RemoteException (and client code must catch
RemoteException). RemoteException means "something
has gone wrong, somewhere outside the JVM."
1.1.3 OutputStream
OutputStream is an abstract class that represents a data sink. Once it is created, client code
can write information to it. OutputStream consists of the following methods:
public void close( ) throws IOException
public void flush( ) throws IOException
public void write(byte[] buffer) throws IOException
public void write(byte[] buffer, int startingOffset, int numberOfBytes)
throws
IOException
public void write(int value) throws IOException
The OutputStream class is a little simpler than InputStream; it doesn't support navigation.
After all, you probably don't want to go back and write information a second time. OutputStream
methods serve two purposes: writing data and resource management.
1.1.3.1 Writing data
OutputStream defines three basic methods for writing data:
public void write(byte[] buffer) throws IOException
public void write(byte[] buffer, int startingOffset, int numberOfBytes)
throws
IOException
public void write(int value) throws IOException
These methods are analogous to the read( ) methods defined for InputStream. Just as there
was one basic method for reading a single byte of data, there is one basic method, write(int
value), for writing a single byte of data. The argument to this write( ) method should be an
integer between 0 and 255. If not, it is reduced to module 256 before being written.
Just as there were two array-based variants of read( ), there are two methods for writing arrays
of bytes. write(byte[] buffer) causes all the bytes in the array to be written out to the