Recipe 10.9 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 set method 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 assume this is somebody else's code; you'll see it 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 Recipe 26.1), a network socket, or URL. Anything that gives you a stream can be used.

See Also

See Recipe 14.9, which shows how to reassign a file so that it gets "written" to a text window in a GUI application.



Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net