座標
<!-- 可以在JVM中可靠地執行外部進程的庫。 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-exec</artifactId>
<version>1.3</version>
</dependency>
其他版本:https://mvnrepository.com/artifact/org.apache.commons/commons-exec
工具類
package com.example.demo.exec;
import org.apache.commons.exec.*;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* 執行系統命令工具類
*
* @author https://blog.csdn.net/chen_2890
*/
public class CommandUtil {
private static Logger logger = LoggerFactory.getLogger(CommandUtil.class.getSimpleName());
private static final String DEFAULT_CHARSET = "UTF-8";
private static final Long TIMEOUT = 10000L;
/**
* 執行指定命令
*
* @param command 命令
* @return 命令執行完成返回結果
* @throws RuntimeException 失敗時拋出異常,由調用者捕獲處理
*/
public synchronized static String exeCommand(String command) throws RuntimeException {
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
int exitCode = exeCommand(command, out);
if (exitCode == 0) {
logger.info("命令運行成功:" + System.currentTimeMillis());
} else {
logger.info("命令運行失敗:" + System.currentTimeMillis());
}
return out.toString(DEFAULT_CHARSET);
} catch (Exception e) {
logger.info(ExceptionUtils.getStackTrace(e));
throw new RuntimeException(ExceptionUtils.getStackTrace(e));
}
}
/**
* 執行指定命令,輸出結果到指定輸出流中
*
* @param command 命令
* @param out 執行結果輸出流
* @return 執行結果狀態碼:執行成功返回0
* @throws ExecuteException 失敗時拋出異常,由調用者捕獲處理
* @throws IOException 失敗時拋出異常,由調用者捕獲處理
*/
public synchronized static int exeCommand(String command, OutputStream out) throws ExecuteException, IOException {
CommandLine commandLine = CommandLine.parse(command);
PumpStreamHandler pumpStreamHandler = null;
if (null == out) {
pumpStreamHandler = new PumpStreamHandler();
} else {
pumpStreamHandler = new PumpStreamHandler(out);
}
// 設置超時時間爲10秒
ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT);
DefaultExecutor executor = new DefaultExecutor();
executor.setStreamHandler(pumpStreamHandler);
executor.setWatchdog(watchdog);
return executor.execute(commandLine);
}
public static void main(String[] args) {
logger.info(exeCommand("pwd"));
logger.info(exeCommand("ls"));
}
}