问题描述
我使用 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!!!