Runtime.getRuntime().exec调用外部程序,在Tomcat下会有当前线程一直等待的现象。
Apache Commons Exec是一个开源的Java调用外部程序类库,提供阻塞和非阻塞方法调用外部程序。
官网地址:
http://commons.apache.org/proper/commons-exec/
Maven:
http://mvnrepository.com/artifact/org.apache.commons/commons-exec
教程:
http://commons.apache.org/proper/commons-exec/tutorial.html
阻塞式使用示例:
String line = "AcroRd32.exe /p /h " + file.getAbsolutePath();
CommandLine cmdLine = CommandLine.parse(line);
DefaultExecutor executor = new DefaultExecutor();
executor.setExitValue(1);
int exitValue = executor.execute(cmdLine);
非阻塞示例+组合参数
CommandLine cmdLine = new CommandLine("AcroRd32.exe");
cmdLine.addArgument("/p");
cmdLine.addArgument("/h");
Map map = new HashMap();
map.put("file", new File("c:\help.pdf"));
cmdLine.addArgument("${file}");
cmdLine.setSubstitutionMap(map);
DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
DefaultExecutor executor = new DefaultExecutor();
executor.setExitValue(1);
executor.execute(cmdLine, resultHandler);
resultHandler.waitFor(); //等待返回