Java執行cmd命令

通常 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()


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章