Running a Program

Problem

You want to run a program.

Solution

Use one of the exec( ) methods in the java.lang.Runtime class.

Discussion

The exec( ) method in the Runtime class lets you run an external program. The command line you give will be broken into strings by a simple StringTokenizer (Section 3.3) and passed on to the operating system’s “execute a program” system call. As a simple example, here is a simple program that uses exec( ) to run kwrite , a windowed text editor program.[59] On MS-Windows, you’d have to change the name to notepad or wordpad, possibly including the full pathname, e.g., c:\\WINDOWS\\NOTEPAD.EXE (double backslashes because the backslash is special in Java strings).

// file ExecDemoSimple.java
public class ExecDemoSimple {
    public static void main(String av[]) throws java.io.IOException { 

        // Run the "notepad" program or a similar editor
        Process p = Runtime.getRuntime(  ).exec("kwrite");

    }
}

When you compile and run it, the appropriate editor window appears:

$ jr ExecDemoSimple
+ jikes +E -d . ExecDemoSimple.java
+ java ExecDemoSimple # causes a KWrite window to appear.
$

Example 26-1 runs the MS-Windows or Unix version of Netscape, assuming Netscape was installed in the default directory. It passes as an argument the name of a help file, offering a kind of primitive “help” mechanism, as displayed in Figure 26-1.

Example 26-1.  ExecDemoNS.java

import com.darwinsys.util.*; import java.awt.event.*; import javax.swing.*; import java.io.*; import java.net.*; import ...

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.