Java Reference
In-Depth Information
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.
Note that the arguments to the redirecting methods must be of the types shown in
the following headings, and these are classes we do not discuss in this topic:
public static void
setIn(InputStream inStream)
public static void
setOut(PrintStream outStream)
public static void
setErr(PrintStream outStream)
None of the input or output streams we constructed in our previous programs are
of a type suitable to be an argument to any of these redirection methods. Space con-
straints keep us from giving any more details on the stream classes that are suitable for
producing arguments for these redirection methods. However, you can use Display
10.10 as a model to allow you to redirect either
System.err
or
System.out
to a text
file of your choice.
Self-Test Exercises
24. Suppose you want the program in Display 10.10 to send an error message to the
screen and regular (
System.out
) output to the file
errormessages.txt
. (Just the
reverse of what the program in Display 10.10 does.) How would you change
the program in Display 10.10?
25. Suppose you want the program in Display 10.10 to send all output (both
System.out
and
System.err
) to the file
errormessages.txt
. How would you
change the program in Display 10.10?
Display 10.10
Redirecting Error Messages
(part 1 of 2)
1
import
java.io.PrintStream;
2
import
java.io.FileOutputStream;
3
import
java.io.FileNotFoundException;
4
public class
RedirectionDemo
5{
6
public static void
main(String[] args)
7
{
8
PrintStream errStream =
null
;
9
try
10
{
(continued)