如何从Groovy脚本重定向输出?
我想知道是否有任何方法可以更改我从Java代码执行的groovy脚本的默认输出(System.out)。
这是Java代码:
public void exec(File file, OutputStream output) throws Exception { GroovyShell shell = new GroovyShell(); shell.evaluate(file); }
以及样本groovy脚本:
def name='World' println "Hello $name!"
目前执行该方法,评估编写“Hello World!”的脚本。 到控制台(System.out)。 如何将输出重定向到作为参数传递的OutputStream?
使用Binding尝试此操作
public void exec(File file, OutputStream output) throws Exception { Binding binding = new Binding() binding.setProperty("out", output) GroovyShell shell = new GroovyShell(binding); shell.evaluate(file); }
评论后
public void exec(File file, OutputStream output) throws Exception { Binding binding = new Binding() binding.setProperty("out", new PrintStream(output)) GroovyShell shell = new GroovyShell(binding); shell.evaluate(file); }
Groovy脚本
def name='World' out << "Hello $name!"
我怀疑你可以通过覆盖GroovyShell的metaClass中的println
方法来做得很好。 以下适用于Groovy控制台:
StringBuilder b = new StringBuilder() this.metaClass.println = { b.append(it) System.out.println it } println "Hello, world!" System.out.println b.toString()
输出:
Hello, world! Hello, world!
使用javax.script.ScriptEngine怎么样? 您可以指定其编写者。
ScriptEngine engine = new ScriptEngineManager().getEngineByName("Groovy"); PrintWriter writer = new PrintWriter(new StringWriter()); engine.getContext().setWriter(writer); engine.getContext().setErrorWriter(writer); engine.eval("println 'HELLO'")
使用SystemOutputInterceptor类。 您可以在脚本评估之前开始拦截输出并在之后停止。
def output = ""; def interceptor = new SystemOutputInterceptor({ output += it; false}); interceptor.start() println("Hello") interceptor.stop()