Java Reference
In-Depth Information
This runs the
who
program (which lists who is logged in to the system, one name per line
along with the terminal port and login time) and sends its output, not to the terminal, but
rather into the standard input of the word count (
wc
) program. Here,
wc
is being asked to
count lines, not words; hence the
-l
option. To
tee
a copy of the intermediate data into a file,
you might say:
who | tee wholist | wc -l
which creates a file
wholist
containing the data. For the curious, the file
wholist
might look
something like this:
ian ttyC0 Mar 14 09:59
ben ttyC3 Mar 14 10:23
ian ttyp4 Mar 14 13:46 (laptop.darwinsys.com)
So both the previous command sequences would print
3
as their output.
TeePrintStream
is an attempt to capture the spirit of the
tee
command. It can be used like
this:
System.setErr(new TeePrintStream(System.err, "err.log"));
// ...lots of code that occasionally writes to System.err... Or might.
System.setErr()
is a means of specifying the destination of text printed to
System.err
(there are also
System.setOut()
and
System.setIn()
). This code results in any messages
that printed to
System.err
to print to wherever
System.err
was previously directed (nor-
mally the terminal, but possibly a text window in an IDE) and in to the file
err.log
.
This technique is not limited to the three standard streams. A
TeePrintStream
can be passed
to any method that wants a
PrintStream
. Or, for that matter, an
OutputStream
. And you
can adapt the technique for
BufferedInputStreams
,
PrintWriters
,
BufferedReaders
,
and so on.
Example 10-7. TeePrintStream
public
public class
extends
PrintStream
{
/** The original/direct print stream */
protected
class
TeePrintStream
TeePrintStream
extends
protected
PrintStream parent
;