read the output from java exec
Use getErrorStream().
BufferedReader in = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
EDIT:
You can use ProcessBuilder (and also read the documentation)
ProcessBuilder ps=new ProcessBuilder("java.exe","-version");//From the DOC: Initially, this property is false, meaning that the //standard output and error output of a subprocess are sent to two //separate streamsps.redirectErrorStream(true);Process pr = ps.start(); BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));String line;while ((line = in.readLine()) != null) { System.out.println(line);}pr.waitFor();System.out.println("ok!");in.close();System.exit(0);
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)
You already have the process-object (name pr). You can get the Input-, Output- and Errorstream. In your case you want pr.getInputStream(). Read from that, that is connected to the output of the process.