S
H
A
R
E

Saturday, February 11, 2012

Java Execute Console Process and Get Output

To execute process you can use ProcessBuilder, like this:

ProcessBuilder pb = new ProcessBuilder("tasklist").redirectErrorStream(true);

use redirectErrorStream to make the BufferedReader can read if error message is returned.

Now, get the Process by executing it:
Process p = pb.start();
  
Then make a BufferedReader that can read the console output screen:
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));

You can read the respond of console process by using while loop like this:

while((str = br.readLine()) != null){
    retVal += str;
}

Here is the complete java function:

Read More!