Java Reference
In-Depth Information
This is a manifestation of the general approach to how Java I/O libraries work. Each I/O
class serves one or a small number of functions. To obtain full functionality you normally
need to combine two (or more) class constructors. For example, in the above example,
the object
new
FileReader("original.txt")
establishes a connection with the file
original.txt
but provides only very primitive methods for input. The constructor for
BufferedReader
takes this file reader object and adds a richer collection of input meth-
ods. In these cases the inner object, such as
new
FileReader("original.txt")
, is trans-
formed into an instance variable of the outer object, such as
BufferedReader
.
Self-Test Exercises
22. Of the classes
PrintWriter
,
Scanner
,
BufferedReader
,
FileReader
, and
File-
OutputStream
, which have a constructor that accepts a file name as an argument
so that the stream created by the constructor invocation is connected to the
named file?
23. Is the following legal?
FileReader readerObject =
new
FileReader("myFile.txt");
BufferedReader inputStream =
new
BufferedReader(readerObject);
System.in
,
System.out
, and
System.err
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 out-
put. 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);