Running External OS Commands from within Java
Return to the Java Programming Corner.
Introduction
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, theRuntimeclass and theProcessclass. In short, you use theexec()method of theRuntimeclass to run the command as a separate process. This returns aProcessobject for managing the subprocess.You then use the
getInputStream()andgetErrorStream()methods of theProcessobject 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 theRuntimeclass. Since you cannot create your own instance of theRuntimeclass, you need to use thegetRuntime()method to access the current runtime environment and then invoke itsexec()method. This will return aProcessobject.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
InputStreamReaderandBufferedReaderso you can use thereadLine()method of the BufferedReader class.