如何登录到一个字符串?有没有办法将每个控制台输出捕获到一个字符串中?

问题描述

我使用 java.util.logging Logger 类,并且 我想捕获控制台上的所有消息(不仅仅是日志)并将它们放入一个字符串中(稍后我会在其他地方使用)。我确实找到了一个println 捕获 System.out-s 的类,但是日志转到 System.err 所以我必须以某种方式包括这些。我试图捕捉他们两个,但我没有找到办法。 我也尝试使用处理程序,但我无法弄清楚。 我怎么解决这个问题?有没有办法将每个控制台输出捕获到一个字符串中?

解决方法

使用 System.setOut(PrintStream ps) 方法,如本例所示:

public class Main{
    public static StringBuffer sb;
    public static void main(String[] args) {
        sb = new StringBuffer();
        PrintStream console = System.out;
        System.setOut(new PrintStream(new OutputStream() {
            
            @Override
            public void write(int b) throws IOException {
                Main.sb.append((char)b);
            }
        }));
        System.out.println("Hello World!!!");//Go to the StringBuffer
        System.out.println("Hello World!!!");//Go to the StringBuffer
        console.println("Output is:\n" + sb);
    }
}

输出为:

Output is:
Hello World!!!
Hello World!!!

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...