2016-04-26 25 views
2

我有一個非常基本的過程:讀取過程輸出都爲OutputStream和字符串

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

這需要很長的時間來運行,所以我想輸出到一個OutputStream在運行時。很容易:

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

但現在我也想輸出爲字符串。我怎麼弄到的?

+2

你可以捕捉它在'StringWriter',然後打印這'系統.out' ...或者使用[commons-io TeeOutputStream](https://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/output/TeeOutputStream.html) –

回答

2

由於@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() 
} 

或者爲還做同樣的事情建議採取雙方在時間,你可以從apache commons-io使用:TeeOutputStreamWriterOutputStream的結果寫入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()