Thursday, February 19, 2009

Java Runtime.Exec() Guide




Everything you ever wanted to know and should know about Java Runtime.exec().

This old but still golden article is an excellent guide to using Runtime.exec(). The key points he discusses are:
1. You need to drain the input stream to prevent because failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.

2. Use waitFor() instead of exitValue() when you want to wait for the process to finish.

3. Runtime.exec() wouldn't directly execute shell commands like dir / ls, copy / cp etc. You need to invoke the shell cmd.exe / bash / sh and pass the shell commands. For example in windows your command array to execute dir would be as follows:
cmd[0] = "cmd.exe" ;
cmd[1] = "/C" ;
cmd[2] = "dir";

Personally I have successfully used Runtime.exec() on several occasions. Any C programmer should quickly find equivalence with fork and system calls in C language. As always RTFM.

No comments: