[ACCEPTED]-How to pipe stdout from a groovy method into a string-groovy

Accepted answer
Score: 13

This demonstrates how you can do this. Paste 6 this into a Groovy script file and run it. You 5 will see the first call functions as normal. The 4 second call produces no results. Finally, the 3 last step in the main prints the results 2 of the second call that were redirected 1 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()
Score: 1

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

More Related questions