Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Process getOutputStream to String

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.

like image 205
smeeb Avatar asked Sep 16 '15 15:09

smeeb


People also ask

What is getOutputStream () in Java?

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.

What is getInputStream in Java?

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.


1 Answers

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
like image 58
Davide Lorenzo MARINO Avatar answered Oct 07 '22 12:10

Davide Lorenzo MARINO