我想知道是否有任何方法可以更改我从 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 http://groovy.codehaus.org/api/groovy/lang/Binding.html
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!"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)