Apache Commons Exec 工具包的使用

來源:互聯網
上載者:User

標籤:

在沒有使用這個工具包之前 我都手寫代碼去執行linux命令的,因為自己寫代碼去執行linux返回的資訊不全,因為寫得很簡單只是調用沒有用線程去等待資訊的返回,也沒有實現失效時間,後來想自己實現但是在無意間找到了這個工具包,能實現我的需求,當時很興奮。

commons exec下載路徑

 

版本下載1.3的版本即可,其實也只有一個版本可下載

1.簡單的命令執行

public static void execLinuxCommand(String command){

  if(StringUtils.isEmpty(command)){

    LOG.info("執行的Linux命令不可為空");

    return ;

  }

  //定義命令列對象

  CommandLine commandLine = new CommandLine(command);

  try{

    //定義執行器對象

    Executor executor = new DefaultExecutor();

    //如果在執行命令結束後發生異常,是因為沒有設定結束標識值

    executor.setExitValue(1);

    executor.execute(commandLine);

  } catch (Exceptiion ex){

    LOG.info("執行Linux命令失敗",ex);

  }

}

2.將執行命令結果資訊

try{

  //定義執行結果資訊輸出

  ByteArrayOutputStream byteStream = new ByteArrayOutputStream();

  //定義失效時間(單位/亳秒)

  ExecuteWatchdog watchdog = new ExecuteWatchdog(3*1000);

  PumpStreamHandler streamHandler = new PumpStreamHandler(byteStream);

  execute.setStreamHandler(streamHandler);

  execute.setWatchdog(watchdog);

}catch(Exception ex){

  

}

在定義StreamHandler後他內建了列印的方法

Apache Commons Exec 工具包的使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.