To execute process you can use ProcessBuilder, like this:
use redirectErrorStream to make the BufferedReader can read if error message is returned.
Now, get the Process by executing it:
You can read the respond of console process by using while loop like this:
Here is the complete java function:
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:
public static String run(String cmd) {
String retVal = "";
try {
ProcessBuilder pb = new ProcessBuilder(cmd).redirectErrorStream(true);
Process p = pb.start();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String str;
while((str = br.readLine()) != null){
retVal += str;
}
} catch (IOException ex) {
retVal = ex.getMessage();
}
return retVal;
}
0 comments:
Post a Comment