How to pipe stdout from a groovy method into a string
groovy
Solution
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()
Problem
How does one invoke a groovy method that prints to stdout, appending the output to a string?