在Java中捕获屏幕截图

6

我正在处理一个类,其中有一个display()函数,用于将一些信息打印到屏幕上。我不允许更改它。有没有一种方法可以在外部“捕获”它打印到屏幕上的字符串?

它会显示在控制台上。


它是如何打印的?以图形方式还是控制台方式? - aioobe
2个回答

5
我能想到的最接近的方法是捕获并转发通过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();
    }
}

重写你想要拦截的方法。(就像上面覆盖了println一样) - aioobe
我的意思是,我如何在原始的System.out处理格式等之后获取字符串? - Amir Rachum
我刚刚用printf成功地完成了这个,但你应该得到采纳的答案,所以请编辑并我会接受(抱歉,我不知道如何在评论中使此代码可读: class 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 Rachum

2
我不熟悉Java中的标准display()操作,这可能是你正在使用的框架所特有的。它会打印到控制台吗?显示一个消息框?
如果您谈论通过System.out.println()System.err.println()输出到控制台的打印输出,则可以。您可以重定向标准输入和标准输出。
使用:
    System.setErr(debugStream);
    System.setOut(debugStream);

并创建适当的流(例如文件)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接