Java Process getOutputStream to String
Asked Answered
B

1

8

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.

Break answered 16/9, 2015 at 15:21 Comment(0)
C
13

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
Compact answered 16/9, 2015 at 15:23 Comment(2)
Thanks @David Lorenzo MARINO (+1) - you seem to be correct, but to me this feels terribly backwards. The app I am running from inside Java (in this particular case, Consul) logs to STDOUT. I would think that the Java Process "wrapping" Consul would make STDOUT available via an OutputStream (it's a stream of chars sent from Consul out to STDOUT). This is correct, and when I can give you the green check in a few mins I will do so, but to the Java Gods I say this: curse you, oh Java Gods, you've got it backwards!!!Break
I added a note to explain why what is an input is really an output and viceversaCompact

© 2022 - 2024 — McMap. All rights reserved.