Sunday, May 08, 2005

Call other program in Java

Today some one asked me about calling other porgram in Java. In java 5.0 beside Runtime.exec() we can use the class Process and ProcessBuilder to have a better control on the execute:

ProcessBuilder:
This class is used to create operating system processes.
Note that this class is not synchronized.
When calling the ProcessBuilder().start() we can get a Process object and monitor the output thru it.

Process p = new ProcessBuilder("ping", "localhost").start();
String line = null;
Scanner in = new Scanner(p.getInputStream());
while (in.hasNextLine()) {
line = in.nextLine();
System.out.printf("%s\n", line);
}
Beside when can get the Environment variables by Map ProcessBuilder().environment() and set our own variable to it, usually the values is a copy of the environment of the current process System.getenv() :
PS. o start a process with an explicit set of environment variables, first call Map.clear() before adding environment variables.
 ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2");
Map env = pb.environment();
env.put("VAR1", "myValue");
env.remove("OTHERVAR");
env.put("VAR2", env.get("VAR1") + "suffix");
pb.directory("myDir");
Process p = pb.start();

Process

It provides Process.getInputStream() and Process.getOutputStream() to read and write data.

No comments: