Tomasz Blachowicz
Tomasz Blachowicz

Reputation: 5843

How to redirect output from Groovy script?

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.

Here is the Java code:

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

And the sample groovy script:

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?

Upvotes: 14

Views: 17411

Answers (5)

David Winslow
David Winslow

Reputation: 8590

System.setOut() is just what you need.

Upvotes: 0

Krzysztof Atłasik
Krzysztof Atłasik

Reputation: 22595

Use SystemOutputInterceptor class. You can start intercepting output before script evaluation and stop after.

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

Upvotes: 3

jjchiw
jjchiw

Reputation: 4425

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

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

Upvotes: 18

Safrain
Safrain

Reputation: 294

How about using javax.script.ScriptEngine? You can specify its writer.

ScriptEngine engine = new ScriptEngineManager().getEngineByName("Groovy");
PrintWriter writer = new PrintWriter(new StringWriter());
engine.getContext().setWriter(writer);
engine.getContext().setErrorWriter(writer);
engine.eval("println 'HELLO'")

Upvotes: 3

Armand
Armand

Reputation: 24333

I suspect you could do this quite nicely by overwriting the println method in your GroovyShell's metaClass. The following works in Groovy Console:

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!

Upvotes: 2

Related Questions