Java Reference
In-Depth Information
Note that the arguments to the redirecting methods must be of the types shown in
the following headings, and that 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
constraints 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 fi le
errormessages.txt
.
(This is 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 fi le
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 {
11 errStream =
12
Note the
stream
classes
used.
new
PrintStream(
13
new
FileOutputStream("errormessages.txt"));
14 }
15
catch
(FileNotFoundException e)
16 {
17 System.out.println(
18 "Error opening file with FileOutputStream.");
19 System.exit(0);
20 }