Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Beginner
Mar 20, 1997

Launching Another Application from Java

Question:
Is it possible to launch another application from a Java application (not an applet)?

Answer:
Yes. There are two classes of interest for performing system level functions such as this:

java.lang.Runtime and
java.lang.Process.

The Runtime class provides several flavors of the exec() method, which takes a command and executes it by creating a separate process using facilities provided by the OS you're running on:

       public Process
exec(String command);
       public Process exec(String command, String envp[]);
       public Process exec(String cmdarray[]);
       public Process exec(String cmdarray[], String envp[]); 
exec() returns an instance of a Process which can then be used by the Java application to interact with the launched program, wait for it to finish, and so on.

The only tricky part in accomplishing this is getting hold of a Runtime object with which to call exec(). To get an instance of a Runtime object, call:

Runtime.getRuntime() 
This method returns a static Runtime object similar to System.out, which is guaranteed to exist for every invocation of the program.

The following program demonstrates how to use these classes to launch an application from a Java program. It takes a command line as its argument and simply executes it as if the user had invoked it. Note that the program captures the output of the launched application by getting an InputStream from the running Process and reading from it as if it were a normal stream.

import java.io.*;

public class CmdExec {

       public CmdExec(String cmdline) {
               try {
                       String line;

                       Process p = Runtime.getRuntime().exec(cmdline);
                       DataInputStream input = new DataInputStream(
                                                       p.getInputStream());
                       while ((line = input.readLine()) != null) {
                               System.out.println(line);
                       }
                       input.close();
               } catch (Exception err) {
                       System.out.println("EXEC failed: " + err.toString());
                       err.printStackTrace();
               }
       }

       public static void main(String argv[]) {
               new CmdExec(argv[0]);
       }

}
 
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date