【问题标题】:Set System.setOut to default console AND a custom output将 System.setOut 设置为默认控制台和自定义输出
【发布时间】:2016-10-27 06:20:08
【问题描述】:

我有一段这样的代码:

System.setOut(new PrintStream(new OutputStream()
{

    @Override
    public void write(int b) throws IOException
    {
        String str = String.valueOf((char) b);
        txtAreaConsole.appendText(str);
    }
}));

但这意味着,我不再在控制台中获得任何信息。 所以我正在寻找这样的东西:

System.setOut(new PrintStream(new OutputStream()
{

    @Override
    public void write(int b) throws IOException
    {
        String str = String.valueOf((char) b);
        txtAreaConsole.appendText(str);
        defaultConsole.appendText(str); //THIS
    }
}));

有类似的吗?谢谢

【问题讨论】:

标签: java string methods console output


【解决方案1】:

当然可以,您只需要“保存”并重用现有的 System.out。

我不知道你代码中的txtAreaConsole是什么,所以我只是在下面的例子中做了一个“MyConsole”:

import java.io.PrintStream;
import java.text.*;

public class Test {

    public Test() {
        System.setOut(new MySystemOut(System.out, new MyConsole()));
        System.out.println("Hey");
    }

    class MyConsole {

        public void appendText(String s) {
            // write text somewhere else here
        }
    }

    class MySystemOut extends PrintStream {

        private final PrintStream out;
        private final MyConsole txtAreaConsole;

        public MySystemOut(PrintStream out, MyConsole txtAreaConsole) {
            super(out);
            this.out = out;
            this.txtAreaConsole = txtAreaConsole;
        }

        @Override
        public void write(int b) {
            String str = String.valueOf((char) b);
            txtAreaConsole.appendText(str);
            out.write(b);
        }

    }

    public static void main(String args[]) throws ParseException {
        new Test();
    }
}

【讨论】:

    【解决方案2】:

    Apache Commons IO 中的TeeOutputStream 正如 Andreas 建议的那样,对我来说是最好的方式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-14
      相关资源
      最近更新 更多