I have a pretty basic process:
Process p = 'foo.exe'.execute()
It takes a long time to run, so I want to output to an OutputStream while it is running. Pretty easy:
p.consumeProcessOutputStream(System.out)
p.waitForOrKill(TIMEOUT_IN_MILLIS)
But now I would also like the output as a String. How can I get that?
As @tim_yates comments you can use StringWriter to save the process result and get the output as String using toString() method:
def sw = new StringWriter()
Process p = 'foo.exe'.execute()
p.consumeProcessOutputStream(sw)
p.waitForOrKill(TIMEOUT_IN_MILLIS)
def processOutput = sw.toString()
If you want to use this String to check your process result, maybe an alternative option is to writer the result to a File, to do so you can do something similar using FileWriter
def fw = new FileWriter("/resultProcess.log")
Process p = 'foo.exe'.execute()
p.consumeProcessOutputStream(fw)
p.waitForOrKill(TIMEOUT_IN_MILLIS)
fw.with {
flush()
close()
}
Or as also @tim_yates suggest to take both at time you can use from apache commons-io: TeeOutputStream and WriterOutputStream to write the result to String and to a 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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With