Reassigning the Standard Streams


You need to reassign one or more of the standard streams, System.out, or System.err.


Construct an InputStream or PrintStream as appropriate, and pass it to the appropriate setmethod in the System class.


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 PrintStream to the variable System.out, you’d be considered antisocial, since there is a defined method to replace it carefully:

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[5];
a[10] = 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. ...

Get Java Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.