我想知道是否有任何方法可以更改我从Java代码执行的groovy脚本的默认输出(System.out).
这是Java代码:
public void exec(File file, OutputStream output) throws Exception {
GroovyShell shell = new GroovyShell();
shell.evaluate(file);
}
Run Code Online (Sandbox Code Playgroud)
和样本groovy脚本:
def name='World'
println "Hello $name!"
Run Code Online (Sandbox Code Playgroud)
目前,该方法的执行,评估编写"Hello World!"的脚本.到控制台(System.out).如何将输出重定向到作为参数传递的OutputStream?
jjc*_*hiw 16
使用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);
}
Run Code Online (Sandbox Code Playgroud)
评论后
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);
}
Run Code Online (Sandbox Code Playgroud)
Groovy脚本
def name='World'
out << "Hello $name!"
Run Code Online (Sandbox Code Playgroud)