使用 Runtime.exec() 執行 Windows 批處理檔時,預設會彈出黑色 CMD 視窗,影響使用者體驗。只需在 start 參數後加上 /b 即可實現靜默執行。
// 會彈出視窗
Runtime.getRuntime().exec("cmd.exe /C start D:\\test.bat");
// 靜默執行,不彈窗
Runtime.getRuntime().exec("cmd.exe /C start /b D:\\test.bat");
Runtime rt = Runtime.getRuntime();
Process ps = null;
try {
ps = rt.exec("cmd.exe /C start /b D:\\test.bat");
} catch (IOException e1) {
e1.printStackTrace();
}
try {
ps.waitFor(); // 阻塞等待結束
int exitCode = ps.exitValue(); // 獲取退出碼
if (exitCode == 0) {
System.out.println("執行完成。");
} else {
System.out.println("執行失敗,退出碼:" + exitCode);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
| 參數 | 作用 |
|---|---|
| /C | 執行完指令字串後終止 CMD |
| start | 啟動獨立視窗執行程式 |
| /b | 不建立新視窗,在當前控制台背景執行(關鍵) |
ProcessBuilder 重定向 stdout/stderr。\"D:\\My Scripts\\test.bat\"。ProcessHandle 進行更精細的程序管理。