Note that we're reading the process output line by line into our StringBuilder
. Due to the try-with-resources
statement we don't need to close the stream manually. The ProcessBuilder
class let's us submit the program name and the number of arguments to its constructor.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ProcessOutputExample
{
public static void main(String[] arguments) throws IOException,
InterruptedException
{
System.out.println(getProcessOutput());
}
public static String getProcessOutput() throws IOException, InterruptedException
{
ProcessBuilder processBuilder = new ProcessBuilder("java",
"-version");
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
StringBuilder processOutput = new StringBuilder();
try (BufferedReader processOutputReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));)
{
String readLine;
while ((readLine = processOutputReader.readLine()) != null)
{
processOutput.append(readLine + System.lineSeparator());
}
process.waitFor();
}
return processOutput.toString().trim();
}
}
Prints:
java version "1.8.0_45"
Java(TM) SE Runtime Environment (build 1.8.0_45-b15)
Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)