Reassigning the Standard Streams
You need to reassign one or more of the standard
PrintStream as appropriate, and pass it to the
appropriate setmethod in the
The ability to reassign these streams corresponds to what Unix (or DOS command line) users think of as redirection, or piping. This mechanism is commonly used to make a program read from or write to a file without having to explicitly open it and go through every line of code changing the read, write, print, etc., calls to refer to a different stream object. The open operation is performed by the command-line interpreter in Unix or DOS, or by the calling class in Java.
While you could just assign a new
System.out, you’d be considered
antisocial, since there is a defined method to replace it carefully:
// Redirect.java String LOGFILENAME = "error.log"; System.setErr(new PrintStream(new FileOutputStream(LOGFILENAME))); System.out.println("Please look for errors in " + LOGFILENAME); // Now to see somebody else's code writing to stderr... int a = new int; a = 0; // here comes an ArrayIndexOutOfBoundsException
The stream you use can be one that you’ve opened, as here, or one you inherited:
System.setErr(System.out); // merge stderr and stdout to same output file.
It could also be a stream connected to or from another
Process you’ve started (see Section 26.2), a network socket, or URL. ...