Executing an External Application in Java

     

There are many times that you might like to launch an application that is running on the user 's machine. For example, an external Web browser could be used to display help pages. There is a way to do this that is as easy as running it yourself from the command line. All you have to know is its name on the system. To make your Java application open Windows Explorer, write

 

 try { Runtime.getRuntime().exec("explorer"); } catch(IOException ioe){ System.out.println(ioe.getMessage()); } 

You have to catch or rethrow the IOException that this call can occasion. Note that we just pass in the system name, not including the file extension.

Passing Arguments to an External Application

Not only can we start an external application, we can pass arguments to it. Instead of allowing Windows Explorer to choose where to open, let's make it bend to our will by passing in the name of the directory in which we would like it to open: the Eclipse IDE workspace directory. We need to make two changes.

 

 try { String[] arg = {"F:\eclipse\workspace"}; Runtime.getRuntime().exec("explorer", arg); } ...//catch statements 

The first thing we've done is we've created an array of Strings with one value, which represents the arguments to our external app. Second, we called the overloaded exec() method that accepts a String array of arguments (sound like any method you're familiar with?), and passed that sucker in.

Java will run the application if it can. Here, we start Windows Explorer, which will open in the Eclipse workspace directory.

This functionality is sometimes employed to start a browser and display a Web page in it. Note that you don't need to know the path to the program you want to launch. If you can type it in a terminal and make it run, it will work here. This functionality is very similar to doing this in Windows: Click Start > Run. Type cmd to get a prompt. Enter explorer F:\eclipse\workspace (or whatever path you want to open). You're good to go.



Java Garage
Java Garage
ISBN: 0321246233
EAN: 2147483647
Year: 2006
Pages: 228
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net