Java 8 Nashorn - capturing engine.eval("print('hello world')) into String object? -
is there way capture result of print('hello world') within nashorn , place in string object.
i have tried this:
bytearrayoutputstream baos = new bytearrayoutputstream(); printstream ps = new printstream(baos, true); system.setout(ps); string result = (string)engine.eval("print('hello world')"); if (result != null) { system.out.println(result); } else { system.out.println(baos.tostring()); } when engine evaluates javascript prints stdout figured redirect stdout own outputstream , convert string, doesn't work.
any thoughts?
you setting system.out stream after have created engine it’s engine’s context has recorded value of system.out/system.err @ construction time.
therefore still see output of script on console. worse, don’t see output of own later-on system.out.println anymore have redirected system.out bytearrayoutputstream.
so don’t modify system.out, instead alter output in context of scripting engine engine.getcontext().setwriter(stringwriter).
complete code:
stringwriter sw=new stringwriter(); engine.getcontext().setwriter(sw); string result = (string)engine.eval("print('hello world')"); system.out.println("result returned eval(): "+result); system.out.println("captured output: "+sw); java java-8 nashorn
No comments:
Post a Comment