Java Process getOutputStream to String

smeeb picture smeeb · Sep 16, 2015 · Viewed 7.7k times · Source

Java 8 here. How does one read the data in Process#getOutputStream() into a String? I am trying to run a process from inside Java and hook/capture its STDOUT.

Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("consul -v");
String capturedOutput;

OutputStream os = proc.getOutputStream();
capturedOutput = howDoIConvert(os);  // <---- ???

Looking for the exact code here (not something vague like baos.toString(codepage). Also interested if I need to close() anything politely.

Answer

Davide Lorenzo MARINO picture Davide Lorenzo MARINO · Sep 16, 2015

You read the data from inputStream not from outputStream.

OutputStream is used to pass data to the process.

There are two basic input streams for Process. One is for standard input and can be retrieved with getInputStream() the other is for errors and can be retrieved with getErrorStream()

From javadoc of getInputStream():

Returns the input stream connected to the normal output of the subprocess

and from getErrorStream()

Returns the input stream connected to the error output of the subprocess.

Note on streams: from the java program perspective a Process is an external program. When you need to add some input to the external program you write from java to that program (so the output of java program is the input of Process). Instead if the external program writes something you read it (so the output of Process is the input for the java program).

Java                   Data direction   External Process
_____________________________________________________________

write to OutputStream  ------------>    read from InputStream
read from InputStream  <------------    write to OutputStream