继承PrintStream类:
public
class
TeeStream
extends
PrintStream {
PrintStream out;
public TeeStream(PrintStream out1, PrintStream out2) {
super (out1);
this .out = out2;
}
public void write( byte buf[], int off, int len) {
try {
super .write(buf, off, len);
out.write(buf, off, len);
} catch (Exception e) {
}
}
public void flush() {
super .flush();
out.flush();
}
}
PrintStream out;
public TeeStream(PrintStream out1, PrintStream out2) {
super (out1);
this .out = out2;
}
public void write( byte buf[], int off, int len) {
try {
super .write(buf, off, len);
out.write(buf, off, len);
} catch (Exception e) {
}
}
public void flush() {
super .flush();
out.flush();
}
}
使用示例:
try
{
PrintStream out = new PrintStream( new FileOutputStream( " out.log " ));
PrintStream tee = new TeeStream(System.out, out);
System.setOut(tee);
PrintStream err = new PrintStream( new FileOutputStream( " err.log " ));
tee = new TeeStream(System.err, err);
System.setErr(tee);
} catch (FileNotFoundException e) {
}
System.out.println( " welcome " );
System.err.println( " error " );
PrintStream out = new PrintStream( new FileOutputStream( " out.log " ));
PrintStream tee = new TeeStream(System.out, out);
System.setOut(tee);
PrintStream err = new PrintStream( new FileOutputStream( " err.log " ));
tee = new TeeStream(System.err, err);
System.setErr(tee);
} catch (FileNotFoundException e) {
}
System.out.println( " welcome " );
System.err.println( " error " );