Java Reference
In-Depth Information
cally represent a particular window on the monitor screen. The System.out and
System.err streams write output to the same window by default (usually the one
in which the program was executed), though they could be set up to write to dif-
ferent places. The System.err stream is usually where error messages are sent.
In addition to the standard input streams, the java.io package of the Java
standard class library provides many classes that let us define streams with par-
ticular characteristics. Some of the classes deal with files, others with memory,
and others with strings. Some classes assume that the data they handle consists
of characters, whereas others assume the data consists of raw bytes of binary
information. Some classes provide the means to manipulate the
data in the stream in some way, such as buffering the information
or numbering it. By combining classes in appropriate ways, we can
create objects that represent a stream of information that has the
exact characteristics we want for a particular situation.
The broad topic of Java I/O, along with the sheer number of classes in the
java.io package, prohibits us from covering it in detail in this topic. Our focus
for the moment is on I/O exceptions.
Many operations performed by I/O classes can potentially throw an
IOException . The IOException class is the parent of several exception classes
that represent problems when trying to perform I/O.
An IOException is a checked exception. As described earlier in this chapter,
that means that either the exception must be caught, or all methods that propa-
gate it must list it in a throws clause of the method header.
Because I/O often deals with external resources, many problems can arise in
programs that attempt to perform I/O operations. For example, a file from which
we want to read might not exist; when we attempt to open the file, an exception
will be thrown, because that file can't be found. In general, we should try to
design programs to be as robust as possible when dealing with potential problems.
We've seen in previous examples how we can use the Scanner class to read and
process input read from a text file. Now let's explore an example that writes data
to a text output file. Writing output to a text file requires simply that we use the
appropriate classes to create the output stream, then call the appropriate methods
to write the data.
Suppose we want to test a program we are writing, but don't have the real data
available. We could write a program that generates a test data file that contains
random values. The program shown in Listing 11.7 generates a file that contains
random integer values within a particular range. It also writes one line of standard
output, confirming that the data file has been written.
KEY CONCEPT
The Java class library contains many
classes for defining I/O streams with
various characteristics.
 
Search WWH ::




Custom Search