Process exec(String command) / Process exec(String[] cmdarray) — 啟動子進程,返回 Process 物件控制輸入/輸出/錯誤流、等待結束、獲取退出碼。
public class LaunchNotepad {
public static void main(String[] args) {
Runtime rt = Runtime.getRuntime();
try {
// Windows 系統路徑已在 PATH 中,可直接用命令名
Process p = rt.exec("notepad.exe");
// 可選:等待結束 int exit = p.waitFor();
} catch (Exception e) {
System.err.println("啟動失敗: " + e.getMessage());
}
}
}
public class LaunchCustomExe {
public static void main(String[] args) {
Runtime rt = Runtime.getRuntime();
try {
// 路徑含空格時,需用雙引號包裹;Java 字串中雙引號需轉義 \"
String cmd = "\"D:/Program Files/MyApp/MyApp.exe\"";
// 或使用 String[] 避免引號轉義麻煩
// String[] cmdArr = {"D:/Program Files/MyApp/MyApp.exe", "arg1", "arg2"};
Process p = rt.exec(cmd);
} catch (Exception e) {
System.err.println("啟動失敗: " + e.getMessage());
}
}
}
Process p = rt.exec("some_command");
// 必須在單獨執行緒消費 stdout/stderr,否則緩衝區滿導致子進程掛起
new Thread(() -> {
try (BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
String line;
while ((line = br.readLine()) != null) System.out.println("[OUT] " + line);
} catch (IOException ignored) {}
}).start();
new Thread(() -> {
try (BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream()))) {
String line;
while ((line = br.readLine()) != null) System.err.println("[ERR] " + line);
} catch (IOException ignored) {}
}).start();
int exitCode = p.waitFor(); // 等待結束
ProcessBuilder pb = new ProcessBuilder("D:/MyApp/MyApp.exe", "arg1", "arg2");
pb.directory(new File("D:/MyApp")); // 設定工作目錄
pb.environment().put("MY_VAR", "value"); // 設定環境變數
pb.redirectErrorStream(true); // 合併 stderr 到 stdout
Process p = pb.start();
// 後續流處理同上
ProcessBuilder API 更豐富、靈活,新專案優先使用。
String[] 或正確轉義引號。pb.directory()。.exe/.bat,Linux/Mac 用腳本/二進制,路徑分隔符不同。