如何重定向Groovy脚本的输出? [英] How to redirect output from Groovy script?

查看:493
本文介绍了如何重定向Groovy脚本的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有任何方法可以改变我从Java代码执行的groovy脚本的默认输出(System.out)。

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代码:

public void exec(File file, OutputStream output) throws Exception {
    GroovyShell shell = new GroovyShell();
    shell.evaluate(file);
}

以及示例groovy脚本:

And the sample groovy script:

def name='World'
println "Hello $name!"

当前执行该方法,评估写入Hello World!的脚本。到控制台(System.out)。如何将输出重定向到作为参数传递的OutputStream?

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?

推荐答案

使用绑定

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脚本

def name='World'
out << "Hello $name!"

这篇关于如何重定向Groovy脚本的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆