目录
Apache Commons Exec 概述
1、从 Java 执行外部进程是一个众所周知的问题领域。它本质上依赖于平台,需要开发人员了解和测试特定于平台的行为,例如在 Windows 上使用 cmd.exe 或导致死锁的有限缓冲区大小。JRE 对此的支持非常有限,尽管使用 Java SE 1.5 ProcessBuilder 类会更好。
2、可靠地执行外部进程还可能需要在执行命令之前或之后了解环境变量。在 J2SE 1.1-1.4 中,不支持此功能,因为用于检索环境变量的 System.getenv()
方法已弃用。
3、官网:https://commons.apache.org/proper/commons-exec/tutorial.html。
Exec 使用快速入门
@Test
public void testExecute1() throws IOException {
// 创建命令行
CommandLine cmdLine = CommandLine.parse("ping www.baidu.com");
// 创建执行器
DefaultExecutor executor = DefaultExecutor.builder().get();
// 设置超时时间
ExecuteWatchdog watchdog = ExecuteWatchdog.builder().setTimeout(Duration.ofMinutes(1)).get();
executor.setWatchdog(watchdog);
// 执行命令
int exitValue = executor.execute(cmdLine);
System.out.println("执行结果:" + exitValue);
}
src/main/java/com/wmx/apachestudy/exec/ExecTest.java · 汪少棠/apache-study - Gitee.com。