重定向javax.script API中KotlinScriptEngine的stdout



我正在使用javax.script API执行kotlin脚本。我想捕获输出并稍后打印日志。

我可以为nashorn脚本引擎做这件事,但同样的事情在KotlinScriptEngine上不起作用。

public void testExampleNashorn() throws ScriptException {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
ScriptContext context = engine.getContext();
StringWriter writer = new StringWriter();
context.setWriter(writer);
engine.eval("print("Welocme to java worldddd")");
String output = writer.toString();
System.out.println("Script output: " + output);
}

Nashorn 的输出

Script output: Welocme to java worldddd

当针对kotlin进行调整时,相同的代码片段如下

public void testExampleKotlin() throws ScriptException {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("kotlin");
ScriptContext context = engine.getContext();
StringWriter writer = new StringWriter();
context.setWriter(writer);
engine.eval("println("Welocme to java worldddd")");
String output = writer.toString();
System.out.println("Script output: " + output);
}

kotlin 的输出

Welocme to java worldddd
Script output: 
null

我使用的是kotlin版本1.3.72非常感谢您的帮助。谢谢

这就是我如何捕获KotlinScriptEngine执行日志的方法。

public Object captureOut(String script,Bindings bindings)  {
Object result=null;
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(os);
PrintStream console = System.out;
System.setOut(ps);
try {
result = kotlinScriptingEngine.eval(script,bindings);
} catch (ScriptException scriptException) {
scriptException.printStackTrace(ps);
}  finally {
System.out.flush();
System.setOut(console);
}
System.out.println("Kotlin Script Output: " + os.toString());
return result;
}

相关内容

  • 没有找到相关文章

最新更新