Srđ*_*vić 3 java java-8 nashorn
有没有办法在Nashorn中捕获print('hello world')的结果并将其放在String对象中.
我试过这个:
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());
}
Run Code Online (Sandbox Code Playgroud)
当引擎评估这个javascript它只是打印到stdout所以我想我只是将stdout重定向到我自己的OutputStream然后将它转换为String,但它不起作用.
有什么想法吗?
您在创建引擎后设置了System.out流,因此引擎的上下文很可能已经在构造时记录了System.out/ 的值System.err.
因此,您仍然可以在控制台上看到脚本的输出.更糟糕的是,System.out.println当你重定向System.out到你的时候,你再也看不到你自己的输出了ByteArrayOutputStream.
所以不要修改System.out,而是在脚本引擎的上下文中更改输出.engine.getContext().setWriter(stringWriter)
完整代码:
StringWriter sw=new StringWriter();
engine.getContext().setWriter(sw);
String result = (String)engine.eval("print('hello world')");
System.out.println("Result returned by eval(): "+result);
System.out.println("Captured output: "+sw);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2146 次 |
| 最近记录: |