ITeye博客

Java重定向System.out和System.err

mmdev · 2007-11-28 10:26 · Markdown

继承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();
}
}

使用示例:

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");

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。