[英]How to pipe stdout from a groovy method into a string
如何調用打印到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”打印到標准輸出。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.