---
title: "Java重定向System.out和System.err"
author: "mmdev"
date: "2007-11-28T10:26:00Z"
tags: []
slug: "java-system-out-system-err"
draft: false
lastmod: "2012-10-29T21:21:19Z"
id: 1708107
url: "https://mmdev.iteye.com/blog/1708107"
---

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