JAVA基础应用——执行外部程序(Apache Commons Exec)

来源:互联网 发布:淘宝退款多了会怎么样 编辑:程序博客网 时间:2024/05/21 12:30

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();  //等待返回
阅读全文
0 1
原创粉丝点击