java 如何重定向 Groovy 脚本的输出?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1531675/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to redirect output from Groovy script?
提问by Tomasz B?achowicz
I wonder if there is any way I could change the default output (System.out) for the groovy script that I'm executing from my Java code.
我想知道是否有任何方法可以更改我从 Java 代码执行的 groovy 脚本的默认输出 (System.out)。
Here is the Java code:
这是Java代码:
public void exec(File file, OutputStream output) throws Exception {
GroovyShell shell = new GroovyShell();
shell.evaluate(file);
}
And the sample groovy script:
和示例 groovy 脚本:
def name='World'
println "Hello $name!"
Currently the execution of the method, evaluates scripts that writes "Hello World!" to the console (System.out). How can I redirect output to the OutputStream passed as a parameter?
当前方法的执行,评估编写“Hello World!”的脚本。到控制台 (System.out)。如何将输出重定向到作为参数传递的 OutputStream?
回答by jjchiw
Try this using 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);
}
After comments
评论后
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 Script
Groovy 脚本
def name='World'
out << "Hello $name!"
回答by Safrain
How about using javax.script.ScriptEngine? You can specify its writer.
使用 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'")
回答by Armand
I suspect you could do this quite nicely by overwriting the printlnmethod in your GroovyShell's metaClass. The following works in Groovy Console:
我怀疑您可以通过覆盖printlnGroovyShell 的元类中的方法来很好地做到这一点。以下在 Groovy 控制台中工作:
StringBuilder b = new StringBuilder()
this.metaClass.println = {
b.append(it)
System.out.println it
}
println "Hello, world!"
System.out.println b.toString()
output:
输出:
Hello, world!
Hello, world!
回答by Krzysztof At?asik
Use SystemOutputInterceptorclass. You can start intercepting output before script evaluation and stop after.
使用SystemOutputInterceptor类。您可以在脚本评估之前开始拦截输出并在之后停止。
def output = "";
def interceptor = new SystemOutputInterceptor({ output += it; false});
interceptor.start()
println("Hello")
interceptor.stop()

