首先自定义一个OutputStream
import java.io.OutputStream;
import javax.swing.JTextArea;
/**
*
* @author 杨庆成 */
public class GuiOutputStream extends OutputStream{
private JTextArea _text;
private byte _c;
private boolean _b=false;
/** Creates a new instance of GuiOutputStream */
public GuiOutputStream(JTextArea text) {
_text=text;
}
public void write(int i){
try{
byte c=(byte)i;
if(_b){
_b=false;
byte[] bs=new byte[2];
bs[0]=_c;
bs[1]=c;
_text.append(new String(bs));
}
else if(c>0){
_b=false;
_text.append(String.valueOf((char)c));
}
else{
_b=true;
_c=c;
}
}
catch(Exception ex){
ex.printStackTrace();
}
}
}
使用方式
重新定向OutputStream
JTextArea jTextArea1 = new javax.swing.JTextArea();
PrintStream out=new PrintStream(new GuiOutputStream(jTextArea1));
System.setOut(out);
Log4j配置文件中Appender设置成org.apache.log4j.ConsoleAppender