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]]
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);
}
}
}
2条答案
按热度按时间z31licg01#
这里有一个简单的方法。只需重写println所需的打印类型。
arraylist包含以下内容:
c86crjj02#
System.out.println
方法有print
以及newLine
方法。没有办法只捕获System.out.println
方法,你应该捕获所有System.out.print
有变化的方法System.out
变量。System.out.println
jdk实现:用于捕获的文本收集器输出流类
System.out.print
内容:测试实施示例: