开发者

Catching screen prints in Java

There's a class I'm working with that has a display() function that prints some information to the screen. I am not allowed to change it. Is there a way to "catch" the string it pri开发者_如何学JAVAnts to the screen externally?

It displays to the console.


The closest thing I can come up with would be to catch and forward everything printed through System.out.

Have a look at the setOut(java.io.PrintStream) method.

A complete example would be:

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


I'm not familiar with a standard display() operation in Java, this might be unique to the framework you're working with. does it print to console? displays a messagebox?

If you are talking about printouts that go through System.out.println() and System.err.println() to the console then yes. You can redirect standard input and standard output. Use:

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

And create the appropriate streams (e.g., files).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜