我想知道是否有任何方法可以更改我从 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);
}
常规脚本
def name='World'
out << "Hello $name!"
关于java - 如何重定向 Groovy 脚本的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1531675/