標籤:
在沒有使用這個工具包之前 我都手寫代碼去執行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 工具包的使用