Running External OS Commands from within Java

Started by ganeshbala, Aug 19, 2008, 10:57 AM

Previous topic - Next topic

ganeshbala

Running External OS Commands from within Java

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, the Runtime class and the Process class. In short, you use the exec() method of the Runtime class to run the command as a separate process. This returns a Process object for managing the subprocess.

    You then use the getInputStream() and getErrorStream() methods of the Process object 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 Runtime class. Since you cannot create your own instance of the Runtime class, you need to use the getRuntime() method to access the current runtime environment and then invoke its exec() method. This will return a Process object.

    From here, everything else you do involves invoking methods of the Process object. 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 InputStreamReader and BufferedReader so you can use the readLine() method of the BufferedReader class.