java 執行Linux命令並打印執行結果

       

/**
 * Shell執行超時時間
 */
  private static final int SHELL_TIME_OUT = 10;

        StringBuilder builder = new StringBuilder("刪除指定文件.log");
        String[] cmd = {"/bin/sh", "-c", "rm -rf "+ builder.toString()};

        Scanner input = null;
        String result = "";
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(cmd);
            // 等待命令執行完成
            process.waitFor(SHELL_TIME_OUT, TimeUnit.SECONDS);
            log.info(" Shell Execute Begin Cmd rm -rf  {}", builder.toString());
            InputStream is = process.getInputStream();
            input = new Scanner(is);
            while (input.hasNextLine()) {
                result += input.nextLine() + "\n";
            }
            log.info(" Shell Execute Result {}", result);
        } catch (InterruptedException | IOException e) {
            e.printStackTrace();
            log.error(" Shell Execute Meets An Error {}", e.getMessage());
        } finally {
            if (null != input) {
                input.close();
            }
            if (null != process) {
                process.destroy();
            }
        }

發佈了13 篇原創文章 · 獲贊 1 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章