tags:

views:

863

answers:

2

How do you invoke a groovy method that prints to stdout, appending the output to a string?

+6  A: 

This demonstrates how you can do this. Paste this into a Groovy script file and run it. You will see the first call functions as normal. The second call produces no results. Finally, the last step in the main prints the results of the second call that were redirected to a ByteArrayOutputStream.

Have fun!

void doSomething() {
  println "i did something"
}

println "normal call\n---------------"
doSomething()
println ""

def buf = new ByteArrayOutputStream()
def newOut = new PrintStream(buf)
def saveOut = System.out

println "redirected call\n---------------"
System.out = newOut
doSomething()
System.out = saveOut
println ""

println "results of call\n---------------"
println buf.toString()
Joe Skora
Worked like a charm! Thanks a lot.
A: 

I'm not sure what you mean by "appending the output to a string", but you can print to standard out using "print" or "println".

Robert Fischer