将进程输出读取到OutputStream和String

时间:2016-04-26 20:52:03

标签: groovy

我有一个非常基本的过程:

Process p = 'foo.exe'.execute()

运行需要很长时间,所以我想在OutputStream运行时输出。很简单:

p.consumeProcessOutputStream(System.out)
p.waitForOrKill(TIMEOUT_IN_MILLIS)

但是现在我还希望输出为String。我怎么能得到它?

1 个答案:

答案 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-ioFileWriterTeeOutputStream来将结果写入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()