Runtime.getRuntime().exec(String) 在 Windows 路徑含空格(如 Program Files)時會解析失敗,改用 exec(String[]) 逐參數傳遞徹底解決。
String cmd = "C:/Program Files (x86)/WinRAR/rar.exe a c:/test.rar c:/test.log";
Process proc = Runtime.getRuntime().exec(cmd); // 空格導致參數分割錯誤
String[] cmd = {
"C:/Program Files (x86)/WinRAR/rar.exe",
"a",
"C:/test.rar",
"c:/test.log"
};
Process proc = Runtime.getRuntime().exec(cmd); // 每個元素為一個獨立參數,無需轉義
Process proc = Runtime.getRuntime().exec(cmd);
try(
InputStream is = proc.getInputStream();
InputStream es = proc.getErrorStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is, "GBK")); // Windows 控制台編碼
){
String line;
while((line = br.readLine()) != null) System.out.println(line);
// 同樣讀取 es 獲取錯誤信息
if(!proc.waitFor(30, TimeUnit.SECONDS)){
proc.destroyForcibly();
throw new TimeoutException("壓縮超時");
}
if(proc.exitValue() != 0) throw new RuntimeException("壓縮失敗 exitCode=" + proc.exitValue());
}
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.redirectErrorStream(true); // 合併錯誤流到輸出流
Process proc = pb.start();
// 後續處理同上
ProcessBuilder 支援工作目錄、環境變量、管道重定向,功能更強,推薦替代 Runtime.exec。
java.util.zip、Apache Commons Compress、Zip4j — 純 Java、無外部依賴、跨平台。exec。