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.
The getOutputStream() method of Java Socket class returns an output stream for the given socket. If you close the returned OutputStream then it will close the linked socket.
getInputStream() method gets the input stream of the subprocess. The stream obtains data piped from the standard output stream of the process represented by this Process object.
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
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