重定向标准输出很easy,System 类里有两个静态方法setErr(PrintStream err) 和 setOut(PrintStream out) 分别用于重定位“标准”错误输出流和“标准”输出流。只需要在程序初始时设置即可:
// GUIPrintStream guiPrintStream = new GUIPrintStream(System.out, jTextArea);
System.setErr(guiPrintStream);
System.setOut(guiPrintStream);
在上面的代码中,我们发现一个新的类 GUIPrintStream,这是我们为 PrintStream 所做的包装。因为我们的输出目标位置是GUI,所以需要在 PrintStream 上做些文章,大家请看下面 GUIPrintStream 的代码:
Java代码
/**//*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.OutputStream;
import java.io.PrintStream;
import javax.swing.SwingUtilities;
import javax.swing.text.JTextComponent;
/** *//**
* 输出到文本组件的流。
*
* @author Chen Wei
* @website www.chenwei.mobi
* @email chenweionline@hotmail.com
*/
public class GUIPrintStream extends PrintStream...{
private JTextComponent component;
private StringBuffer sb = new StringBuffer();
public GUIPrintStream(OutputStream out, JTextComponent component)...{
super(out);
this.component = component;