1、引入依赖
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-exec -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-exec</artifactId>
<version>1.3</version>
</dependency>
2、代码编写测试
public static void main(String[] args) throws IOException {
System.out.println("==================");
CommandLine cmdLine = new CommandLine("ping");
cmdLine.addArgument("www.baidu.com");
// cmdLine.addArgument("-t");
//cmdLine.setSubstitutionMap(Collections.singletonMap("host", "www.baidu.com"));
// 阻塞
DefaultExecutor defaultExecutor = new DefaultExecutor();
// 看门狗(timeout)
ExecuteWatchdog watchdog = new ExecuteWatchdog(10 * 1000);
defaultExecutor.setWatchdog(watchdog);
//defaultExecutor.setExitValue(1); //不设置默认为0
// 获取命令运行中的流程(一般流操作会在多线程中操作)
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ByteArrayOutputStream errorOutPutStream = new ByteArrayOutputStream();
PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream, errorOutPutStream);
defaultExecutor.setStreamHandler(pumpStreamHandler);
int exitValue = defaultExecutor.execute(cmdLine);
System.out.println(exitValue); //返回的结果
System.out.println(outputStream.toString("gbk"));
System.out.println(errorOutPutStream.toString("gbk"));
}
![]()