我有一个非常基本的过程:
Process p = 'foo.exe'.execute()
运行需要很长时间,所以我想在OutputStream运行时输出。很简单:
p.consumeProcessOutputStream(System.out)
p.waitForOrKill(TIMEOUT_IN_MILLIS)
但是现在我还希望输出为String。我怎么能得到它?
答案 0 :(得分:2)
作为@tim_yates评论,您可以使用StringWriter
保存处理结果,并使用String
方法将输出设为toString()
:
def sw = new StringWriter()
Process p = 'foo.exe'.execute()
p.consumeProcessOutputStream(sw)
p.waitForOrKill(TIMEOUT_IN_MILLIS)
def processOutput = sw.toString()
如果您想使用此String
来检查您的流程结果,可能另一种选择是将结果写入File
,为此您可以使用{{3}执行类似操作}
def fw = new FileWriter("/resultProcess.log")
Process p = 'foo.exe'.execute()
p.consumeProcessOutputStream(fw)
p.waitForOrKill(TIMEOUT_IN_MILLIS)
fw.with {
flush()
close()
}
或者同样@tim_yates
建议你可以同时使用apache commons-io
:FileWriter
和TeeOutputStream
来将结果写入String
并且File
:
@Grab('commons-io:commons-io:2.5')
import org.apache.commons.io.output.TeeOutputStream
import org.apache.commons.io.output.WriterOutputStream
// File outputresult
def wosFw = new WriterOutputStream( new FileWriter("/resultProcess.log") )
// String output result
def sw = new StringWriter()
def wosSw = new WriterOutputStream( sw )
// create teeOutputStream with two outputStreams
def teeOS = new TeeOutputStream(wosFw,wosSw)
Process p = 'foo.exe'.execute()
p.consumeProcessOutputStream(teeOS)
p.waitForOrKill(TIMEOUT_IN_MILLIS)
teeOS.with {
flush()
close()
}
def resultProcess = sw.toString()