简体   繁体   English

如何将stdout从groovy方法传递到字符串中

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

如何调用打印到stdout的groovy方法,将输出附加到字符串?

This demonstrates how you can do this. 这演示了如何执行此操作。 Paste this into a Groovy script file and run it. 将其粘贴到Groovy脚本文件中并运行它。 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. 最后,main中的最后一步打印重定向到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()

我不确定你的意思是“将输出附加到字符串”,但你可以使用“print”或“println”打印到标准输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM