invoking a command line tool from within by java applciation
I have a command line tool that I want to launch f开发者_运维问答rom a java application. My application should then wait for the command line tool to return/finish. I will deploy my application on windows, mac and linux and my app should be able to invoke the command line tool on every platform. How can I properly invoke it from my java application?
http://download.oracle.com/javase/1.5.0/docs/api/java/lang/ProcessBuilder.html
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Process.html
ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2");
Process p = pb.start();
p.waitFor();
Use java.lang.Process for that:
final Process process = Runtime.getRuntime().exec("yourprogram", null, outputDir);
final int exitCode = process.waitFor();
if (exitCode != 0) {
throw new RuntimeException("program didnt exit with 0, but with " + exitCode);
}
You can use the Runtime
class to start command line program. You should be able to use in Win/Mac/Linux by making sure that the command line program you are running is always in the PATH.
Runtime rt = Runtime.getRuntime();
Process proc;
proc = rt.exec(cmdName);
// Wait for the command to complete.
exitVal = proc.waitFor();
精彩评论