How could I read Java Console Output into a String buffer -
i have java program outputs text console. uses print
, println
, , other methods this.
at end of program , want read text in console , copy string buffer. how in java ? need read stdout
, stderr
separately.
ok, fun problem. dosen't seem elegant way of solving printstream
methods @ once. (unfortunately there no filterprintstream
.)
i did write ugly reflection-based workaround though (not used in production code suppose :)
class loggedprintstream extends printstream { final stringbuilder buf; final printstream underlying; loggedprintstream(stringbuilder sb, outputstream os, printstream ul) { super(os); this.buf = sb; this.underlying = ul; } public static loggedprintstream create(printstream tolog) { try { final stringbuilder sb = new stringbuilder(); field f = filteroutputstream.class.getdeclaredfield("out"); f.setaccessible(true); outputstream psout = (outputstream) f.get(tolog); return new loggedprintstream(sb, new filteroutputstream(psout) { public void write(int b) throws ioexception { super.write(b); sb.append((char) b); } }, tolog); } catch (nosuchfieldexception shouldnothappen) { } catch (illegalargumentexception shouldnothappen) { } catch (illegalaccessexception shouldnothappen) { } return null; } }
...that can used this:
public class test { public static void main(string[] args) { // create logged printstreams loggedprintstream lpsout = loggedprintstream.create(system.out); loggedprintstream lpserr = loggedprintstream.create(system.err); // set them stdout / stderr system.setout(lpsout); system.seterr(lpserr); // print stuff system.out.print("hello "); system.out.println(5); system.out.flush(); system.err.println("some error"); system.err.flush(); // restore system.out / system.err system.setout(lpsout.underlying); system.seterr(lpserr.underlying); // print logged output system.out.println("----- log system.out: -----\n" + lpsout.buf); system.out.println("----- log system.err: -----\n" + lpserr.buf); } }
resulting output:
hello 5 error ----- log system.out: ----- hello 5 ----- log system.err: ----- error
(note though, out
field in filteroutputstream
protected , documented, part of api :-)
Comments
Post a Comment