| API | 優點 | 缺點 | 推薦場景 |
|---|---|---|---|
| Runtime.getRuntime().exec() | 簡單、舊版相容 | 參數處理麻煩、無建構者模式、錯誤流需手動讀取 | 簡單單一指令 |
| ProcessBuilder | 參數列表型安全、支援目錄/環境變數/管道、可重導向輸出 | API 較繁瑣 | 複雜指令、生產環境 |
| Apache Commons Exec | 超時、監看、結果處理器、依賴管理 | 第三方依賴 | 企業級應用 |
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.*;
public class ShellExecutor {
private static final int DEFAULT_TIMEOUT_SEC = 30;
private static final int BUFFER_SIZE = 8192;
public static class Result {
public final int exitCode;
public final String stdout;
public final String stderr;
public final boolean timedOut;
public final long durationMs;
private Result(int exitCode, String stdout, String stderr, boolean timedOut, long durationMs) {
this.exitCode = exitCode;
this.stdout = stdout;
this.stderr = stderr;
this.timedOut = timedOut;
this.durationMs = durationMs;
}
public boolean isSuccess() { return exitCode == 0 && !timedOut; }
@Override public String toString() {
return String.format("Result[exit=%d, timeout=%b, duration=%dms, stdout=%d chars, stderr=%d chars]",
exitCode, timedOut, durationMs, stdout.length(), stderr.length());
}
}
public static Result execute(List command) {
return execute(command, DEFAULT_TIMEOUT_SEC);
}
public static Result execute(List command, int timeoutSeconds) {
return execute(command, timeoutSeconds, null, null);
}
public static Result execute(List command, int timeoutSeconds,
Map env, File workingDir) {
long start = System.currentTimeMillis();
ProcessBuilder pb = new ProcessBuilder(command);
if (env != null) pb.environment().putAll(env);
if (workingDir != null) pb.directory(workingDir);
// 合併錯誤流到標準輸出 (避免雙緩衝區死鎖)
pb.redirectErrorStream(true);
try {
Process process = pb.start();
// 非同步讀取輸出
StringBuilder output = new StringBuilder();
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8), BUFFER_SIZE)) {
String line;
while ((line = reader.readLine()) != null) {
output.append(line).append('\n');
}
}
// 等待結束或超時
boolean finished = process.waitFor(timeoutSeconds, TimeUnit.SECONDS);
long duration = System.currentTimeMillis() - start;
if (!finished) {
process.destroyForcibly().waitFor(1, TimeUnit.SECONDS);
return new Result(-1, output.toString(), "Timeout after " + timeoutSeconds + "s", true, duration);
}
return new Result(process.exitValue(), output.toString(), "", false, duration);
} catch (IOException | InterruptedException e) {
Thread.currentThread().interrupt(); // 保留中斷狀態
return new Result(-1, "", e.getMessage(), false, System.currentTimeMillis() - start);
}
}
// 便利方法:字串指令自動分割 (簡單場景)
public static Result execute(String command, int timeoutSeconds) {
return execute(Arrays.asList(command.split("\\s+")), timeoutSeconds);
}
}
public class Demo {
public static void main(String[] args) {
// 1. 簡單指令
Result r1 = ShellExecutor.execute("ls -la /tmp");
System.out.println(r1);
System.out.println(r1.stdout);
// 2. 複雜指令含參數 (避免空格分割問題)
Result r2 = ShellExecutor.execute(Arrays.asList(
"find", "/var/log", "-name", "*.log", "-mtime", "-7"
), 60);
System.out.println(r2);
// 3. 環境變數與工作目錄
Map env = new HashMap<>();
env.put("CUSTOM_VAR", "test123");
Result r3 = ShellExecutor.execute(Arrays.asList("bash", "-c", "echo $CUSTOM_VAR"),
10, env, new File("/tmp"));
System.out.println(r3.stdout.trim()); // test123
// 4. 管道指令 (需 shell 解析)
Result r4 = ShellExecutor.execute(Arrays.asList("bash", "-c", "ps aux | grep java | head -5"), 10);
System.out.println(r4.stdout);
}
}
public static void executeStreaming(List command,
Consumer stdoutHandler,
Consumer stderrHandler,
int timeoutSeconds) throws IOException, InterruptedException {
ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectErrorStream(false); // 分離 stdout/stderr
Process process = pb.start();
ExecutorService executor = Executors.newFixedThreadPool(2);
Future> stdoutFuture = executor.submit(() -> {
try (BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
String line;
while ((line = br.readLine()) != null) stdoutHandler.accept(line);
}
});
Future> stderrFuture = executor.submit(() -> {
try (BufferedReader br = new BufferedReader(new InputStreamReader(process.getErrorStream()))) {
String line;
while ((line = br.readLine()) != null) stderrHandler.accept(line);
}
});
try {
boolean finished = process.waitFor(timeoutSeconds, TimeUnit.SECONDS);
if (!finished) process.destroyForcibly();
} finally {
executor.shutdownNow();
try { executor.awaitTermination(1, TimeUnit.SECONDS); } catch (InterruptedException ignored) {}
}
}
// 使用:即時顯示建構日誌
ShellExecutor.executeStreaming(
Arrays.asList("./gradlew", "build"),
line -> System.out.println("[OUT] " + line),
line -> System.err.println("[ERR] " + line),
300
);
pb.redirectErrorStream(true) 合併流,或啟動兩執行緒同時讀取List 逐個參數傳遞,或 bash -c "cmd"C:\\\\path 或用正斜線 C:/pathsudo (需免密設定)pb.environment() 只影響子進程,不影響 JVMList 參數化Java 執行 Shell 腳本首選 ProcessBuilder,封裝工具類統一處理超時、編碼、雙流讀取、錯誤處理。複雜場景引入 Apache Commons Exec。嚴防命令注入,生產環境務必審計記錄。