Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect output from Groovy script?

Tags:

java

groovy

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?

like image 808
Tomasz Błachowicz Avatar asked Oct 07 '09 13:10

Tomasz Błachowicz


2 Answers

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!"
like image 62
jjchiw Avatar answered Nov 10 '22 19:11

jjchiw


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'")
like image 3
Safrain Avatar answered Nov 10 '22 20:11

Safrain