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?
Edit: it displays to the console.
views:
60answers:
2
+5
A:
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();
}
}
aioobe
2010-05-21 14:48:23
@aioobe How do I do this with `printf(String format,String)` ?
Amir Rachum
2010-05-21 20:33:46
Override the method you want to intercept. (just as println is overidden above)
aioobe
2010-05-21 20:40:23
@aioobe I meant, how do I get the string after the original `System.out` worked out the format, etc. ?
Amir Rachum
2010-05-21 20:56:14
If I understand you correctly, it's not possible.
aioobe
2010-05-21 21:32:55
@aioobe I succeeded in doing this with printf just now, but you deserve the accepted answer, so edit this in and I'll accept (sorry, I don't know how to make this code readable in the comment: 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
2010-05-21 22:13:22
+2
A:
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).
Uri
2010-05-21 14:49:05