How to redirect output from Groovy script?
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!"
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'")