/**
* TeePrintStream tees all PrintStream operations into a file, rather like the
* UNIX tee(1) command. It is a PrintStream subclass. The expected usage would
* be something like the following:
*
* <PRE>
*
* ... TeePrintStream ts = new TeePrintStream(System.err, "err.log");
* System.setErr(ts); // ...lots of code that occasionally writes to
* System.err... ts.close(); ...
*
* <PRE>
*
* <P>
* I only override Constructors, the write(), check() and close() methods, since
* any of the print() or println() methods must go through these. Thanks to
* Svante Karlsson for help formulating this.
*
* @author Ian F. Darwin, [url=http://www.darwinsys.com/]Ian Darwin: Java/Python/Unix Consultant/Speaker[/url]
* @version $Id: TeePrintStream.java 132 2011-10-26 12:30:47Z kaf9tr $
*/
public class TeePrintStream extends PrintStream {
/** A simple test case. */
public static void main(final String[] args) throws IOException {
final TeePrintStream ts = new TeePrintStream(System.err, "err.log", true);
System.setErr(ts);
System.err.println("An imitation error message");
ts.close();
}
protected PrintStream parent;
protected String fileName;
/**
* Construct a TeePrintStream given an existing PrintStream and an opened
* OutputStream.
*/
public TeePrintStream(final PrintStream orig, final OutputStream os) throws IOException {
this(orig, os, true);
}
/**
* Construct a TeePrintStream given an existing PrintStream, an opened
* OutputStream, and a boolean to control auto-flush. This is the main
* constructor, to which others delegate via "this".
*/
public TeePrintStream(final PrintStream orig, final OutputStream os, final boolean flush) throws IOException {
super(os, true);
fileName = "(opened Stream)";
parent = orig;
}
/*
* Construct a TeePrintStream given an existing Stream and a filename.
*/
public TeePrintStream(final PrintStream os, final String fn) throws IOException {
this(os, fn, true);
}
/*
* Construct a TeePrintStream given an existing Stream, a filename, and a
* boolean to control the flush operation.
*/
public TeePrintStream(final PrintStream orig, final String fn, final boolean flush) throws IOException {
this(orig, new FileOutputStream(fn), flush);
}
/**
* Return true if either stream has an error.
*/
@Override
public boolean checkError() {
return parent.checkError() || super.checkError();
}
/**
* Close both streams.
*/
@Override
public void close() {
parent.close();
super.close();
}
/**
* Flush both streams.
*/
@Override
public void flush() {
parent.flush();
super.flush();
}
/**
* override write(). This is the actual "tee" operation.
*/
@Override
public void write(final byte[] x, final int o, final int l) {
parent.write(x, o, l); // "write once;
super.write(x, o, l); // write somewhere else."
}
/**
* override write(). This is the actual "tee" operation.
*/
@Override
public void write(final int x) {
parent.write(x); // "write once;
super.write(x); // write somewhere else."
}
}