Here is an example that shows how to execute a process (similar to typing a command at the command line), read the output of the process execution, and determine whether the execution succeeds based on the return value of the process. In general, a process that returns 0 indicates a successful execution and other values indicate failure.
Import java.io.*;
/**
* Example: Executing a process and returning a result
*/
public class Processexecutor {
public static final int SUCCESS = 0; Indicates successful program execution
public static final String COMMAND = "Java.exe-version"; The statement to execute
public static final String success_message = "program executed successfully!" ";
public static final String error_message = "Program execution error:";
public static void Main (string[] args) throws Exception {
Execute the program
Process process = Runtime.getruntime (). exec (COMMAND);
Print program output
Readprocessoutput (process);
Wait for program execution to end and 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) {
Prints the normal output of the process in System.out, and the error output of the process is printed in System.err
Read (Process.getinputstream (), System.out);
Read (Process.geterrorstream (), system.err);
}
Read 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 ();
}
}
}
Related
Java runs the system command line and gets the return value
Java example: How to execute a process and read the output