之前使用 Runtime.getRuntime().exec 调用外部程序。在 Tomcat 下会有当前线程一直等待的现象。
当时为了解决问题,使用新建线程接收外部程序的输出信息。详情请看博客 http://blog.csdn.net/accountwcx/article/details/46785437。
后来在网上找到开源的 Java 调用外部程序类库 Apache Commons Exce,这个类库提供非堵塞方法调用外部程序。
官方网址
http://commons.apache.org/proper/commons-exec/
maven 地址
http://mvnrepository.com/artifact/org.apache.commons/commons-exec/1.3
官方教程 http://commons.apache.org/proper/commons-exec/tutorial.html 官方教程提供的非堵塞方法在 1.3 版中不适用
Commons Exec 对调用外部程序进行了封装,仅仅须要少量代码就可以实现外部程序调用。如运行命令 "AcroRd32.exe /p /h c:\help.pdf"。
- String line = "AcroRd32.exe /p /h c:\help.pdf";
- CommandLine cmdLine = CommandLine.parse(line);
- DefaultExecutor executor = new DefaultExecutor();
- //设置命令运行退出值为1,假设命令成功运行而且没有错误,则返回1
- executor.setExitValue(1);
- int exitValue = executor.execute(cmdLine);
Commons Exec 支持通过加入參数方式构建命令。运行命令 "AcroRd32.exe /p /h c:\help.pdf" 也能够按例如以下方法创建。
- 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);
- DefaultExecutor executor = new DefaultExecutor();
- executor.setExitValue(1);
- int exitValue = executor.execute(cmdLine);
Commons Exec 支持设置外部命令运行等待时间,假设超过等等时间则中断运行。
- 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);
- DefaultExecutor executor = new DefaultExecutor();
- //创建监控时间60秒,超过60秒则中端运行
- ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000);
- executor.setWatchdog(watchdog);
- executor.setExitValue(1);
- int exitValue = executor.execute(cmdLine);
上面的运行外部命令都是堵塞式。也就是在运行外部命令时,当前线程是堵塞的。假设不想在运行外部命令的时候,把当前线程堵塞,能够使用 DefaultExecuteResultHandler 处理外部命令运行的结果。释放当前线程。
- 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();
博客 http://blog.csdn.net/accountwcx/article/details/46785437 的 HtmlToPdf 类能够改成例如以下。
来源: http://www.bubuko.com/infodetail-2230674.html