When Runtime.exec() won't
Reference:http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.htmlAs part of the Java language, the java.lang package is implicitly imported into every Java program. This package's pitfalls surface often, affecting most programmers. This month, I'll discuss the traps lurking in the Runtime.exec() method.
When Runtime.exec() won't
The class java.lang.Runtime features a static method called getRuntime(), which retrieves the current Java Runtime Environment. That is the only way to obtain a reference to the Runtime object. With that reference, you can run external programs by invoking the Runtime class's exec() method. Developers often call this method to launch a browser for displaying a help page in HTML.
There are four overloaded versions of the exec() command:
[*]public Process exec(String command);
[*]public Process exec(String [] cmdArray);
[*]public Process exec(String command, String [] envp);
[*]public Process exec(String [] cmdArray, String [] envp);
Foreach of these methods, a command -- and possibly a set of arguments --is passed to an operating-system-specific function call. Thissubsequently creates an operating-system-specific process (a runningprogram) with a reference to a Process class returned to the Java VM. The Process class is an abstract class, because a specific subclass of Process exists for each operating system.
You can pass three possible input parameters into these methods:
[*]A single string that represents both the program to execute and any arguments to that program
[*]An array of strings that separate the program from its arguments
[*]An array of environment variables
Pass in the environment variables in the form name=value. If you use the version of exec() with a single string for both the program and its arguments, note that the string is parsed using white space as the delimiter via the StringTokenizer class.
Stumbling into an IllegalThreadStateException
The first pitfall relating to Runtime.exec() is the IllegalThreadStateException. The prevalent first test of an API is to code its most obvious methods. For example, to execute a process that is external to the Java VM, we use the exec() method. To see the value that the external process returns, we use the exitValue() method on the Process class. In our first example, we will attempt to execute the Java compiler (javac.exe):
Listing 4.1 BadExecJavac.java
import java.util.*;import java.io.*;public class BadExecJavac{ public static void main(String args[]) { try { Runtime rt = Runtime.getRuntime(); Process proc = rt.exec("javac"); int exitVal = proc.exitValue(); System.out.println("Process exitValue: " + exitVal); } catch (Throwable t) { t.printStackTrace(); } }}
页:
[1]