题
如何调用打印到stdout的groovy方法,将输出附加到字符串?
解决方案
这说明了如何做到这一点。将其粘贴到Groovy脚本文件中并运行它。您将看到第一个呼叫功能正常。第二次调用没有结果。最后,main中的最后一步打印重定向到ByteArrayOutputStream的第二个调用的结果。
玩得开心!
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()
其他提示
我不确定你的意思是“将输出附加到字符串”,但是你可以使用“print”打印到标准输出。或“println”。
不隶属于 StackOverflow