O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Reassigning the Standard Streams

Problem

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

Solution

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

Discussion

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:

// 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[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. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required