簡體   English   中英

如何登錄到字符串? 有沒有辦法將每個控制台 output 捕獲到單個字符串中?

[英]How to log into a string? Is there a way to capture every console output into a single string?

我使用java.util.logging Logger class,我想捕獲控制台上的所有消息(不僅僅是日志)並將它們放在一個字符串中(我稍后會在其他地方使用)。 我確實找到了一個 class ,它從System.out捕獲println -s,但是日志 go 到System.err所以我必須以某種方式包括這些。 我試圖抓住他們兩個,但我沒有找到辦法。 我也嘗試使用處理程序,但我無法弄清楚它們。 我怎么解決這個問題? 有沒有辦法將每個控制台 output 捕獲到單個字符串中?

使用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 是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM