printing - Get console text in java -
is there way retrieve output console has been outputted by:
system.out.print("blabla");
?
if want able see wrote console, need write own printstream
implementation wraps existing printstream
, stores whatever supposed write , delegates (all methods) wrapped (original) printstream
actual job. how store messages entirely depends on needs (store last written string, store map of timestamp -> string or whatever). once have this, can replace system.out
own implementation (via system.setout()
):
public class rememberallwrittentextprintstream extends printstream { private static final string newline = system.getproperty("line.separator"); private final stringbuffer sb = new stringbuffer(); private final printstream original; public rememberallwrittentextprintstream(printstream original) { this.original = original; } public void print(double d) { sb.append(d); original.print(d); } public void print(string s) { sb.append(s); original.print(s); } public void println(string s) { sb.append(s).append(newline); original.println(s); } public void println() { sb.append(newline); original.println(); } public void printf(string s, object... args) { sb.append( string.format(s, args) ); original.printf(s, args); } // ..... // same public methods in printstream.... // (your ide should create delegates `original` methods.) public string getallwrittentext() { return sb.tostring(); } }
you may need take care of thread-safety (stringbuffer thread-safe, may need more this).
once have above, can:
rememberallwrittentextprintstream ps = new rememberallwrittentextprintstream(system.out); system.setout(ps); system.out.print("bla"); system.out.print("bla"); ps.getallwrittentext(); // should return "blabla"
edit: added println()
implementations using platform-independent newline
.
Comments
Post a Comment