Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read the output from java exec

Hello i have some question about java. here is my code:

public static void main(String[] args) throws Exception {     Process pr = Runtime.getRuntime().exec("java -version");      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); } 

in that code i'am trying to get a java version command execute is ok, but i can't read the output it just return null. Why?

like image 341
maxormo Avatar asked Nov 16 '11 10:11

maxormo


People also ask

How to read the output In Java?

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.

What is exec method in Java?

exec(String command) method executes the specified string command in a separate process. This is a convenience method. An invocation of the form exec(command) behaves in exactly the same way as the invocation exec(command, null, null).

What is ProcessBuilder in Java?

public ProcessBuilder(String... command) Constructs a process builder with the specified operating system program and arguments. This is a convenience constructor that sets the process builder's command to a string list containing the same strings as the command array, in the same order.


1 Answers

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 streams ps.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); 
like image 99
KV Prajapati Avatar answered Sep 28 '22 09:09

KV Prajapati