继承PrintStream类:
publicclassTeeStreamextendsPrintStream{
PrintStreamout;
publicTeeStream(PrintStreamout1,PrintStreamout2){
super(out1);
this.out=out2;
}
publicvoidwrite(bytebuf[],intoff,intlen){
try{
super.write(buf,off,len);
out.write(buf,off,len);
}catch(Exceptione){
}
}
publicvoidflush(){
super.flush();
out.flush();
}
}
PrintStreamout;
publicTeeStream(PrintStreamout1,PrintStreamout2){
super(out1);
this.out=out2;
}
publicvoidwrite(bytebuf[],intoff,intlen){
try{
super.write(buf,off,len);
out.write(buf,off,len);
}catch(Exceptione){
}
}
publicvoidflush(){
super.flush();
out.flush();
}
}
使用示例:
try{
PrintStreamout=newPrintStream(newFileOutputStream("out.log"));
PrintStreamtee=newTeeStream(System.out,out);
System.setOut(tee);
PrintStreamerr=newPrintStream(newFileOutputStream("err.log"));
tee=newTeeStream(System.err,err);
System.setErr(tee);
}catch(FileNotFoundExceptione){
}
System.out.println("welcome");
System.err.println("error");
PrintStreamout=newPrintStream(newFileOutputStream("out.log"));
PrintStreamtee=newTeeStream(System.out,out);
System.setOut(tee);
PrintStreamerr=newPrintStream(newFileOutputStream("err.log"));
tee=newTeeStream(System.err,err);
System.setErr(tee);
}catch(FileNotFoundExceptione){
}
System.out.println("welcome");
System.err.println("error");