tags:

views:

406

answers:

2

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?

+2  A: 

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

Groovy Script

def name='World'
out << "Hello $name!"
jjchiw
That would work, but I'd like to redirect *any* output written to the standard output. Especially by built-in functions such us println().
pregzt
You were *about* right. The solution is to wrap the output int the java.io.PrintStream and pass as "out" property to the shell!
pregzt
yay!, my first bronze badge!Happy it work it out! How did you wrap the output?
jjchiw
Congrats! Simply use new PrintStream(output) and pass as "out" property to binding.
pregzt
A: 

http://java.sun.com/j2se/1.3/docs/api/java/lang/System.html#setOut%28java.io.PrintStream%29 is just what you need.

David Winslow
I'm afraid System.setOut is too heavyweight :) It changes the output globally for the entire JVM and this is not something that I wanted to do :)
pregzt