如何将所有 system.out.println 捕获到数组或字符串列表

How to capture all system.out.println to an array or list of string

我想弄清楚如何将所有 System.out.println 存储到字符串列表中,就像任何时候一样 System.out.println 调用后会作为List的一个元素存储。

我已经知道我们可以使用 System.setOut() 捕获 System.out.print。

提前致谢。

System.out.println 方法有 printnewLine 方法。无法只捕获 System.out.println 方法,您应该通过更改 System.out 变量来捕获所有 System.out.print 方法。

System.out.println jdk 实施:

    public void println(String x) {
        synchronized (this) {
            print(x);
            newLine();
        }
    }

用于捕获 System.out.print 内容的文本收集器输出流 class:

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

public class TextCollector extends OutputStream {
    private final List<String> lines = new ArrayList<>();
    private StringBuilder buffer = new StringBuilder();

    @Override
    public void write(int b) throws IOException {
        if (b == '\n') {
            lines.add(buffer.toString());
            buffer = new StringBuilder();
        } else {
            buffer.append((char) b);
        }
    }

    public List<String> getLines() {
        return lines;
    }
}

示例测试实现:

import java.util.*;
import java.io.*;

public class Main {
    public static void main(String[] args) {
        // store current output
        PrintStream tmpOut = System.out;

        // change stream into text collector
        TextCollector textCollector = new TextCollector();
        System.setOut(new PrintStream(textCollector));

        // collect lines
        System.out.println("Test-1");
        System.out.println("Test-2");

        // print lines to console
        System.setOut(tmpOut);
        List<String> lines = textCollector.getLines();
        for (String line : lines) {
            System.out.println(line);
        }
    }
}

这是一个简单的方法。只需覆盖您需要为 println 打印的类型即可。

public class MyPrintStreamDemo extends PrintStream {
    static List<Object> list = new ArrayList<>();
    static PrintStream orig = System.out; 
    public MyPrintStreamDemo() {
        // any print method not overridden will print normally.
        // If you want to suppress non-overridden output
        // set the first argument below to PrintStream.nullOutputStream()
        super(System.out, true);
    }
    
    
    public static void main(String[] args) {
        System.setOut(new MyPrintStreamDemo());
        System.out.println("This is a test");
        System.out.println("And so is this");
        System.out.println(10);
        System.out.println(20.222);
        System.out.println(List.of(1,2,3,4));
        orig.println(list);
    }
    
    
    public void println(String s) {
        list.add(s);
    }
    public void println(double s) {
        list.add(s);
    }
    public void println(int s) {
        list.add(s);
    }
    public void println(Object s) {
        list.add(s);
    }
}

ArrayList 包含以下内容:

[This is a test, And so is this, 10, 20.222, [1, 2, 3, 4]]