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
2008-09-23 15:34:14
Worked like a charm! Thanks a lot.
2008-09-23 16:20:59
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
2008-10-13 19:44:12