Developer

Access the native OS through Runtime.exec()

When you need to run a program from Java, Runtime.exec() provides a simple way to do it. This tip will show you how.


Java developers sometimes hit a wall because the Java APIs are simply incapable of providing needed functionality. For complex needs, you can turn to the Java Native Interface (JNI) to access shared libraries directly. But in many cases, Runtime.exec() can be a simpler solution.

The minimal requirement to use this command is an array of strings that include the executable name (and optional path), followed by each of the arguments to pass to the program. The exec() method itself then returns a java.lang.Process object that can be used to get output data from the called application and to check for the application to exit. You can also pass environment variables to the new process if needed.

Listing A  shows an example of how to display the output from the ping command (presuming ping is available on your system).

Runtime.exec() is not a perfect solution. It requires predetermined knowledge of the name and possibly the location of the called application and does not perform any of the actions normally associated with a shell such as I/O redirection. Before using it, you should review the java.lang.Runtime and java.lang.Process documentation. However, if your needs are relatively simple, Runtime.exec() is by far the easiest way to pull native functionality into your Java application.

Getting more out of your Java app
What are some ways you get more functionality out of your Java applications? Share your tips and suggestions by sending us an e-mail with your suggestions, or post a comment below.

 

Editor's Picks