Java Reference
In-Depth Information
on the opposite side of the I/O fence. The external program's output becomes
our input.)
Example 4.4 shows a Java program that can invoke an arbitrary Linux
program. The output of the program is displayed.
Example 4.4 Java program to execute any Linux program
import java.io.*;
public class
Exec
{
public static void
main(String [] args)
throws IOException
{
String ln;
Process p = Runtime.getRuntime().exec(args);
BufferedReader br = new BufferedReader(
new InputStreamReader(
p.getInputStream()));
while((ln = br.readLine()) != null) {
System.out.println(ln);
}
System.out.println("returns:" + p.exitValue());
} // main
} // class Exec
The command-line arguments are taken to be the command to be execut-
ed and its arguments. For example:
$ java Exec ls -l
Be aware that in this example, only the standard output is captured and
displayed from the invoked process. Error messages written to standard err
will be lost, unless you modify the program to handle this. We leave that as an
exercise for the reader.
Check your Linux knowledge—see if you understand the distinction. If
you invoke the sample Exec program as:
Search WWH ::




Custom Search