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.
The Java Printing API enables applications to: Print all AWT and Java 2D graphics, including composited graphics and images.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With