java執行命令行,以及解決卡死問題

java能夠執行本地命令行,可是有一個坑,命令執行後,已經執行完畢,可是卡死不返回,這是由於:java

命令會返回兩個輸出流,正確的返回流,和錯誤的返回流緩存

通常程序的作法是先循環讀正確的返回流,再讀錯誤的返回流,當正確的返回流讀不完的時候,有可能錯誤的返回流已經佔滿了緩存,因此致使了卡死,app

解決辦法是:ui

1.單獨起一個線程讀取錯誤流,這樣的狀況下,錯誤流比較很差保存spa

2.使用ProcessBuild類,這個類能夠把錯誤流重定向到正確流,這樣只讀一個流就能夠了,不論正確或錯誤,都能讀到返回,下面是個例子命令行

ProcessBuilder pb;
Process process = null;
BufferedReader br = null;
StringBuilder resMsg = null;
OutputStream os = null;
String cmd1 = "sh";
try {
    pb = new ProcessBuilder(cmd1);
    pb.redirectErrorStream(true);
    process = pb.start();
    os = process.getOutputStream();
    os.write(command.getBytes());
    os.flush();
    os.close();

    resMsg = new StringBuilder();
    // get command result
    if (isNeedResultMsg) {
        br = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String s;
        while ((s = br.readLine()) != null) {
            resMsg.append(s + "\n");
        }
        resMsg.deleteCharAt(resMsg.length()-1);
        result = process.waitFor();
    }
} catch (IOException e) {
    e.printStackTrace();
} catch (Exception e) {
    e.printStackTrace();
} finally {
    try {
        if (os != null) {
            os.close();
        }
        if (br != null) {
            br.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (process != null) {
        process.destroy();
    }
}
return resMsg.toString();
相關文章
相關標籤/搜索