通常 Java 執行 Windows 或者 Linux 的命令時,都是使用 Runtime.getRuntime.exec(command)
來執行的
eg1: 執行命令
public static void execCommand() {
try {
Runtime runtime = Runtime.getRuntime();
// 打開任務管理器,exec方法調用后返回 Process 進程對象
Process process = runtime.exec("cmd.exe /c taskmgr");
// 等待進程對象執行完成,並返回“退出值”,0 為正常,其他為異常
int exitValue = process.waitFor();
System.out.println("exitValue: " + exitValue);
// 銷毀process對象
process.destroy();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
eg2: 執行命令,並獲取正常輸出與錯誤輸出
public static void execCommandAndGetOutput() {
try {
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("cmd.exe /c ipconfig");
// 輸出結果,必須寫在 waitFor 之前
String outStr = getStreamStr(process.getInputStream());
// 錯誤結果,必須寫在 waitFor 之前
String errStr = getStreamStr(process.getErrorStream());
int exitValue = process.waitFor(); // 退出值 0 為正常,其他為異常
System.out.println("exitValue: " + exitValue);
System.out.println("outStr: " + outStr);
System.out.println("errStr: " + errStr);
process.destroy();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
public static String getStreamStr(InputStream is) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(is, "GBK"));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
br.close();
return sb.toString();
}
process
對象可以通過操作數據流,對執行的命令進行參數輸入、獲取命令輸出結果、獲取錯誤結果
getInputStream() |
獲取process進程的輸出數據 |
---|---|
getOutputStream() |
獲取process進程的輸入數據 |
getErrorStream() |
獲取process進程的錯誤數據 |
值得注意的是:
getInputStream()
為什么是獲取輸出數據?getOutputStream()
為什么是獲取輸入數據?這是因為 input 和 output 是針對當前調用 process 的程序而言的,即
要獲取命令的輸出結果,就是被執行命令的結果 輸入到我們自己寫的程序中,所以用getInputStream()
要往別的程序輸入數據,就是我們程序要輸出,所以此時用getOutputStream()