如何将所有system.out.println捕获到一个数组或字符串列表中
我试图弄清楚如何将所有 System.out.println 存储到一个字符串列表中,就像在任何时候调用 System.out.println 一样,它将被存储为 List 的一个元素。
我已经知道我们可以使用 System.setOut() 捕获 System.out.print。
先感谢您。
回答
System.out.println方法有print和newLine方法。没有办法只捕获System.out.println方法,您应该捕获所有System.out.print具有变化System.out变量的方法。
System.out.println jdk实现:
public void println(String x) {
synchronized (this) {
print(x);
newLine();
}
}
用于捕获System.out.print内容的文本收集器输出流类:
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);
}
}
}
THE END
二维码