gpt4 book ai didi

groovy - 将进程输出读取到 OutputStream 和 String

转载 作者:行者123 更新时间:2023-12-01 14:45:38 24 4
gpt4 key购买 nike

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

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

需要很长时间才能运行,所以我想在它运行时输出到一个OutputStream。很简单:

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

但现在我还想将输出作为字符串。我怎样才能得到它?

最佳答案

作为@tim_yates 的评论,您可以使用 StringWriter使用 toString() 方法保存处理结果并以 String 形式输出:

def sw = new StringWriter()

Process p = 'foo.exe'.execute()
p.consumeProcessOutputStream(sw)
p.waitForOrKill(TIMEOUT_IN_MILLIS)

def processOutput = sw.toString()

如果你想使用这个 String 来检查你的处理结果,也许另一种选择是将结果写入 File,为此你可以做一些事情类似使用 FileWriter

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 的时候同时使用这两个:TeeOutputStreamWriterOutputStream将结果写入 StringFile:

@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()

关于groovy - 将进程输出读取到 OutputStream 和 String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36875499/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com