我正在处理一个类,其中有一个display()
函数,用于将一些信息打印到屏幕上。我不允许更改它。有没有一种方法可以在外部“捕获”它打印到屏幕上的字符串?
它会显示在控制台上。
我正在处理一个类,其中有一个display()
函数,用于将一些信息打印到屏幕上。我不允许更改它。有没有一种方法可以在外部“捕获”它打印到屏幕上的字符串?
它会显示在控制台上。
System.out
打印出的所有内容。setOut(java.io.PrintStream)
方法。import java.io.PrintStream;
public class Test {
public static void display() {
System.out.println("Displaying!");
}
public static void main(String... args) throws Exception {
final List<String> outputLog = new ArrayList<String>();
System.setOut(new PrintStream(System.out) {
public void println(String x) {
super.println(x);
outputLog.add(x);
}
// to "log" printf calls:
public PrintStream printf(String format, Object... args) {
outputLog.add(String.format(format, args));
return this;
}
});
display();
}
}
System.out
处理格式等之后获取字符串? - Amir Rachumclass Printer extends PrintStream {
public List<String> strList;
public Printer(OutputStream out) {
super(out);
this.strList = new LinkedList<String>();
}
public PrintStream printf(String format, Object... args) {
strList.add(String.format(format, args));
return this;
}} - Amir RachumSystem.out.println()
和System.err.println()
输出到控制台的打印输出,则可以。您可以重定向标准输入和标准输出。 System.setErr(debugStream);
System.setOut(debugStream);
并创建适当的流(例如文件)。