2010-05-21 128 views
6

我正在使用的一个类有一个display()函数,它可以在屏幕上打印一些信息。我不能改变它。有没有办法“抓住”从外部打印到屏幕上的字符串?在Java中捕捉屏幕打印

它显示在控制台上。

+0

它如何打印?图形,还是控制台? – aioobe 2010-05-21 14:45:02

回答

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(); 
    } 
} 
+0

如何使用'printf(String format,String)'做到这一点? – 2010-05-21 20:33:46

+0

重写您想截取的方法。 (就像println在上面一样) – aioobe 2010-05-21 20:40:23

+0

我的意思是,在最初的'System.out'制定出格式之后,我怎么得到字符串? – 2010-05-21 20:56:14

2

我不熟悉标准显示在Java中()操作,这可能是唯一的,你正在使用的框架。它打印到控制台?显示一个消息框?

如果您正在讨论打印输出通过System.out.println()System.err.println()到控制台,那么是的。您可以重定向标准输入和标准输出。 使用:

System.setErr(debugStream); 
    System.setOut(debugStream); 

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