Java Reference
In-Depth Information
Self-Test Exercises
22. Of the classes
PrintWriter
,
Scanner
,
BufferedReader
,
FileReader
, and
FileOutputStream
, which have a constructor that accepts a fi le name as an
argument so that the stream created by the constructor invocation is connected
to the named fi le?
23. Is the following legal?
FileReader readerObject =
new
FileReader("myFile.txt");
BufferedReader inputStream =
new
BufferedReader(readerObject);
The streams
System.in
,
System.out
, and
System.err
are three streams that are
automatically available to your Java code. You have already been using
System.in
and
System.out
.
System.err
is just like
System.out
, except that it has a different name.
For example, both of the following statements will send the string
"Hello"
to the
screen so the screen receives two lines, each containing
"Hello"
:
System.out.println("Hello");
System.err.println("Hello");
The output stream
System.out
is intended to be used for normal output from code
that is not in trouble.
System.err
is meant to be used for error messages.
Having two different standard output streams can be handy when you redirect
output. For example, you can redirect the regular output to one file and redirect the
error messages to a different file. Java allows you to redirect any of these three standard
streams to or from a file (or other I/O device). This is done with the static methods
setIn
,
setOut
, and
setErr
of the class
System
.
For example, suppose your code connects the output stream
errStream
(of a type
to be specified later) to a text file. You can then redirect the stream
System.err
to this
text file as follows:
redirecting
output
System.setErr(errStream);
If the following appears later in your code,
System.out.println("Hello from System.out.");
System.err.println("Hello from System.err.");
then
"Hello from System.out."
will be written to the screen, but
"Hello from
System.err."
will be written to the file connected to the output stream
errStream
.
A simple program illustrating this is given in Display 10.10.