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 java.awt.*;

/**
 * ExecDemoNS shows how to execute a 32-bit Windows program from within Java.
 */
public class ExecDemoNS extends JFrame {
    /** The name of the help file. */
    protected final static String HELPFILE = "./help/index.html";

    /** The path to the Netscape binary  */
    protected static String netscape;

    /** A process object tracks one external running process */
    Process p;

    /** main - instantiate and run */
    public static void main(String av[]) throws Exception { 
        new ExecDemoNS(  ).setVisible(true);
    }

    /** Constructor - set up strings and things. */
    public ExecDemoNS(  ) {
        super("ExecDemo: Netscape");
        String osname = System.getProperty("os.name");
        if (osname == null) 
            throw new IllegalArgumentException("no os.name");
        netscape = // Windows or Unix only for now, sorry Mac fans
            (osname.toLowerCase(  ).indexOf("windows")!=-1) ?
            "c:/program files/netscape/communicator/program/netscape.exe" :
            "/usr/local/netscape/netscape";

        Container cp = getContentPane(  );
        cp.setLayout(new FlowLayout(  ));
        JButton b;
        cp.add(b=new JButton("Exec"));
        b.addActionListener(new ActionListener(  ) {
            public void actionPerformed(ActionEvent evt) {
                doHelp(  );
            }
        });
        cp.add(b=new JButton("Wait"));
        b.addActionListener(new ActionListener(  ) {
            public void actionPerformed(ActionEvent evt) {
                doWait(  );
            }
        });
        cp.add(b=new JButton("Exit"));
        b.addActionListener(new ActionListener(  ) {
            public void actionPerformed(ActionEvent evt) {
                System.exit(0);
            }
        });
        pack(  );
    }

    /** Start the help, in its own Thread. */
    public void doHelp(  ) {

        new Thread(  ) {
            public void run(  ) {

                try {
                    // Get the URL for the Help File
                    URL helpURL = this.getClass().getClassLoader(  ).
                        getResource(HELPFILE);

                    // Start Netscape from the Java Application. A Java
                    // Applet would not be allowed to, nor need to :-)

                    p = Runtime.getRuntime(  ).exec(netscape + " " + helpURL);

                    Debug.println("trace", "In main after exec");

                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(ExecDemoNS.this,
                        "Error" + ex, "Error",
                        JOptionPane.ERROR_MESSAGE);
                }
            }
        }.start(  );

    }

    public void doWait(  ) {
        try {
            p.waitFor(  );    // wait for process to complete
            Debug.println("trace", "Process is done");
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this,
                "Error" + ex, "Error",
                JOptionPane.ERROR_MESSAGE);
        }
    }

}
ExecDemoNS in action

Figure 26-1.  ExecDemoNS in action



[59] kwrite is Unix-specific; it’s a part of the K Desktop Environment (KDE). See http://www.kde.org.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.133.54