[英]How to log into a string? Is there a way to capture every console output into a single string?
I use the java.util.logging
Logger
class, and I would like to capture all messages on the console (not just the logs) and put them in a string (that I use later elsewhere).我使用java.util.logging
Logger
class,我想捕获控制台上的所有消息(不仅仅是日志)并将它们放在一个字符串中(我稍后会在其他地方使用)。 I did find a class that captures the println
-s from System.out
, but the logs go to System.err
so I have to include those as well somehow.我确实找到了一个 class ,它从System.out
捕获println
-s,但是日志 go 到System.err
所以我必须以某种方式包括这些。 I have tried to capture both of them, but I didn't find a way.我试图抓住他们两个,但我没有找到办法。 I also tried to use handlers but I couldn't figure them out.我也尝试使用处理程序,但我无法弄清楚它们。 How can I solve this problem?我怎么解决这个问题? Is there a way to capture every console output into a single string?有没有办法将每个控制台 output 捕获到单个字符串中?
Use System.setOut(PrintStream ps)
method, like in this example:使用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);
}
}
The output is: output 是:
Output is:
Hello World!!!
Hello World!!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.