继承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");
本文介绍了一个名为TeeStream的类,该类继承自PrintStream,用于将输出同时发送到两个目的地。通过构造函数初始化两个输出流,并重写了write和flush方法以确保数据被正确发送。示例展示了如何设置系统输出流和错误流来使用TeeStream。
2686

被折叠的 条评论
为什么被折叠?



