// ... definition of plugTogether ...
This code assumes that a method plugTogether exists to connect two streams by reading the bytes from
one stream and writing them onto the other.
The second way a Process object represents the child process is by providing methods to control the
process and discover its termination status:
public abstract intwaitFor()tHRows InterruptedException
Waits indefinitely for the process to complete, returning the value it passed to
either System.exit or its equivalent (zero means success, nonzero means
failure). If the process has already completed, the value is simply returned.
public abstract intexitValue()
Returns the exit value for the process. If the process has not completed,
exitValue throws IllegalThreadStateException.
public abstract voiddestroy()
Kills the process. Does nothing if the process has already completed.
Garbage collection of a Process object does not mean that the process is
destroyed; it will merely be unavailable for manipulation.
For example, the following method returns a String array that contains the output of the ls command with
the specified command-line arguments. It throws an LSFailedException if the command completed
unsuccessfully:
// We have imported java.io. and java.util.
public String[] ls(String dir, String opts)
throws LSFailedException
{
try {
// start up the command
String[] cmdArray = { "/bin/ls", opts, dir };
Process child = Runtime.getRuntime().exec(cmdArray);
InputStream lsOut = child.getInputStream();
InputStreamReader r = new InputStreamReader(lsOut);
BufferedReader in = new BufferedReader(r);
// read the command's output
List
String line;
while ((line = in.readLine()) != null)
lines.add(line);
if (child.waitFor() != 0) // if the ls failed
throw new LSFailedException(child.exitValue());
return lines.toArray(new String[lines.size()]);
} catch (LSFailedException e) {
throw e;
} catch (Exception e) {
throw new LSFailedException(e.toString());
}
}