Running External OS Commands from within Java
Return to the Java Programming Corner.
After seeing an example of how to run an external OS command from within a Java application is the easiest way to explain how to accomplish this task. It involves the use of two Java classes, the
Runtimeclass and the
Processclass. In short, you use the
exec()method of the
Runtimeclass to run the command as a separate process. This returns a
Processobject for managing the subprocess.
You then use the
getErrorStream()methods of the
Processobject to read the normal output of the command, and the error output of the command. What you do with the output of the command executed is entirely up to you and the application you're creating.
How it all works
The first task is to specify the OS command you want to run by supplying this command as a String to the
Runtimeclass. Since you cannot create your own instance of the
Runtimeclass, you need to use the
getRuntime()method to access the current runtime environment and then invoke its
exec()method. This will return a
From here, everything else you do involves invoking methods of the
Processobject. For simple cases, like when running the "ps -ef" command in UNIX, you only need to read the output of the command. You also have the option of reading from standard error, but in most cases this isn't necessary but does provide for good programming practice.
Many example will require you to convert the input streams with the
BufferedReaderso you can use the
readLine()method of the BufferedReader class.