将System.setOut设置为默认控制台和自定义输出

问题描述 投票:-1回答:2

我有一段这样的代码:

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
2个回答
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();
    }
}

0
投票

正如安德烈亚斯所说,来自TeeOutputStreamApache Commons IO对我来说是最好的方式。

© www.soinside.com 2019 - 2024. All rights reserved.