簡體   English   中英

如何重定向 Groovy 腳本的輸出?

[英]How to redirect output from Groovy script?

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

使用綁定試試這個

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);
}

Groovy 腳本

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

使用 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'")

使用SystemOutputInterceptor類。 您可以在腳本評估之前開始攔截輸出並在之后停止。

def output = "";
def interceptor = new SystemOutputInterceptor({ output += it; false});
interceptor.start()
println("Hello")
interceptor.stop()

我懷疑您可以通過覆蓋 GroovyShell 的元類中的println方法來很好地做到這一點。 以下在 Groovy 控制台中工作:

StringBuilder b = new StringBuilder()

this.metaClass.println = {
    b.append(it)
    System.out.println it
}

println "Hello, world!"
System.out.println b.toString()

輸出:

Hello, world!
Hello, world!

System.setOut()正是您所需要的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM