java - 如何重定向 Groovy 脚本的输出?

标签 java groovy

我想知道是否有任何方法可以更改我从 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/

相关文章:

Java 惰性字符串流,包括 List<String>

groovy - 访问为 Jenkins Groovy 插件脚本指定的变量

grails - 在Grails自定义标签库中查找父标签

groovy - 使用 elvis 运算符抛出异常 Groovy

java - 如何在eclipse中安装Hibernate

java - RCP 应用程序未重新启动

java - 查找插入位置

Java - 在构造函数中设置变量后,有什么方法可以使变量不可修改?

java - 按日期降序排序列表 - groovy madness

jenkins - 需要帮助使用 groovy 和 Jenkins 读取 json 文件