Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching screen prints in Java

Tags:

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 prints to the screen externally?

It displays to the console.

like image 531
Amir Rachum Avatar asked May 21 '10 14:05

Amir Rachum


People also ask

Can I print image in Java?

The Java Printing API enables applications to: Print all AWT and Java 2D graphics, including composited graphics and images.

How do you print a page in Java?

In Java, we usually use the println() method to print the statement. It belongs to the PrintStream class. The class also provides the other methods for the same purpose.

What is printable in Java?

The Printable interface is implemented by the print methods of the current page painter, which is called by the printing system to render a page. When building a Pageable , pairs of PageFormat instances and instances that implement this interface are used to describe each page.


2 Answers

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();
    }
}
like image 160
aioobe Avatar answered Nov 08 '22 03:11

aioobe


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).

like image 39
Uri Avatar answered Nov 08 '22 03:11

Uri