Java example: how to execute a process and read the output

Source: Internet
Author: User

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 ();
}
}
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.