The following example shows how to execute a process (similar to typing a command under the command line), read the output of the Process execution, and determine whether the execution is successful Based on the return value of the process. Generally, if the process returns 0, the execution is successful, and other values indicate failure.
Import java. io .*;
/**
* Example: Execute the process and return results
*/
Public class ProcessExecutor {
Public static final int SUCCESS = 0; // indicates that the program is successfully executed.
Public static final String COMMAND = "java.exe-version"; // The statement to be executed
Public static final String SUCCESS_MESSAGE = "the program is successfully executed! ";
Public static final String ERROR_MESSAGE = "program execution error :";
Public static void main (String [] args) throws Exception {
// Execute the program
Process process = runtime.getruntime(cmd.exe c (COMMAND );
// Print program output
ReadProcessOutput (process );
// Wait until the program execution ends and the output status
Int exitCode = process. waitFor ();
If (exitCode = SUCCESS ){
System. out. println (SUCCESS_MESSAGE );
} Else {
System. err. println (ERROR_MESSAGE + exitCode );
}
}
/**
* Print process output
*
* @ Param process
*/
Private static void readProcessOutput (final Process process ){
// Print the normal output of the Process in System. out, and print the error output in System. err.
Read (process. getInputStream (), System. out );
Read (process. getErrorStream (), System. err );
}
// Read the input stream
Private static void read (InputStream inputStream, PrintStream out ){
Try {
BufferedReader reader = new BufferedReader (new InputStreamReader (inputStream ));
String line;
While (line = reader. readLine ())! = Null ){
Out. println (line );
}
} Catch (IOException e ){
E. printStackTrace ();
} Finally {
Try {
InputStream. close ();
} Catch (IOException e ){
E. printStackTrace ();
}
}
}
}