Java操作shell腳本

public class Exec {

private static ILogger logger = LoggerFactory.getLogger(Exec.class);

public Exec() {
super();
}


? ? /**
? ? ?* 執行命令(如Shell腳本)<br>
? ? ?*?
? ? ?* @param cmd 操作命令
? ? ?* @param timeout 超時時間
? ? ?* @return 命令執行過程輸出內容
? ? ?*?
? ? ?* @throws IOException
? ? ?* @throws TimeoutException
? ? ?* @throws InterruptedException
? ? ?*/
? ? public String execute(final String cmd, final long timeout) throws IOException, TimeoutException, InterruptedException{
? ? if(cmd == null || cmd.trim().length() == 0) {
? ? return null;
? ? }
? ? long time = 1000L * 5;
? ? time = timeout > 0 ? timeout : time;
? ? ? ??
? ? long begin = System.currentTimeMillis();
? ?
? ? logger.info("Begin execute command { " + cmd + " }, timeout = " + time + " seconds.");
? ? ? ??
? ? //執行命令
? ? Process process = Runtime.getRuntime().exec(cmd);?
? ? ? ??
? ? ? ? TimeWorker timeWorker = new TimeWorker(process);
? ? ? ? process.getOutputStream().close();
? ? ? ? OutputWorker outputWorker = new OutputWorker(process.getInputStream());
? ? ? ? String result = null;
? ? ? ? outputWorker.start();
? ? ? ? timeWorker.start();
? ? ? ? try {
? ? ? ?
? ? ? ? //任務超時
? ? ? ? ? ? timeWorker.join(time);
? ? ? ? ? ? if (timeWorker.exit == null) {
? ? ? ? ? ? ? ? throw new TimeoutException(cmd);
? ? ? ? ? ? } else if(timeWorker.exit != 0) {
? ? ? ? ? ? logger.error("Execute command " + cmd + " error, error message: " + this.getOutput(process.getErrorStream()));
? ? ? ? ? ? ? ? result = "error";
? ? ? ? ? ? } else {
? ? ? ? ? ? ? ? result = outputWorker.output;
? ? ? ? ? ? }
? ? ? ? } catch (InterruptedException e) {
? ? ? ? ? ? timeWorker.interrupt();
? ? ? ? ? ? Thread.currentThread().interrupt();
? ? ? ? ? ? throw e;
? ? ? ? } finally {
? ? ? ? ? ? process.destroy();
? ? ? ? }
? ? ? ??
? ? ? ? long end = System.currentTimeMillis();
? ? ? ? logger.info("Finish execute command { " + cmd + " }, time spent " + (end - begin)/1000L + " seconds.");
? ?
? ? return result;
? ? }
? ??
? ? /**
? ? ?* 獲取IO輸出內容 <br>
? ? ?*?
? ? ?* @param stream 流
? ? ?* @return 內容
? ? ?* @throws IOException
? ? ?*/
? ? private String getOutput(InputStream stream) throws IOException {
? ? if(stream == null) {
? ? return null;
? ? }
? ? ? ? StringBuffer buffer = new StringBuffer();
? ? ? ? BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
? ? ? ? String line = null;
? ? ? ? while((line = reader.readLine()) != null) {
? ? ? ? ? ? buffer.append(line + "\n");
? ? ? ? }
? ? ? ? reader.close();
? ? ? ? return buffer.toString().trim();
? ? }
? ??
? ? /**
? ? ?*?
? ? ?* @author?
? ? ?*
? ? ?*/
? ? private static class OutputWorker extends Thread {
? ?
? ? ? ? private final InputStream stream;
? ? ? ? private String output = null;


? ? ? ? private OutputWorker(InputStream stream) {
? ? ? ? ? ? this.stream = stream;
? ? ? ? }
? ? ? ??
? ? ? ? public void ?run() {
? ? ? ? ? ? String line = null;
? ? ? ? ? ? StringBuffer buffer=new StringBuffer();
? ? ? ? ? ? BufferedReader reader=null;
? ? ? ? ? ? try {
? ? ? ? ? ? ? ? reader = new BufferedReader(new InputStreamReader(stream));
? ? ? ? ? ? ? ? while((line = reader.readLine()) != null) {
? ? ? ? ? ? ? ? ? ? buffer.append(line+"\n");
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? this.output = buffer.toString().trim();
? ? ? ? ? ? } catch (IOException e) {
? ? ? ? ? ? logger.error(e.getMessage());
? ? ? ? ? ? } finally {
? ? ? ? ? ? ? ? if(reader!=null) {
? ? ? ? ? ? ? ? ? ? try {
? ? ? ? ? ? ? ? ? ? ? ? reader.close();
? ? ? ? ? ? ? ? ? ? } catch (IOException e) {
? ? ? ? ? ? ? ? ? ? logger.error(e.getMessage());
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? }


? ? }
? ??
? ? /**
? ? ?*?
? ? ?* @author
? ? ?*
? ? ?*/
? ? private static class TimeWorker extends Thread {
? ?
? ? ? ? private final Process process;
? ? ? ??
? ? ? ? private Integer exit = null;


? ? ? ? private TimeWorker(Process process) {
? ? ? ? ? ? this.process = process;
? ? ? ? }
? ? ? ??
? ? ? ? public void run() {
? ? ? ? ? ? try {
? ? ? ? ? ? //阻塞等待命令執行結束
? ? ? ? ? ? ? ? exit = process.waitFor();
? ? ? ? ? ? } catch (InterruptedException e) {
? ? ? ? ? ? logger.error(e.getMessage());
? ? ? ? ? ? }
? ? ? ? }
? ? }
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/273400.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/273400.shtml
英文地址,請注明出處:http://en.pswp.cn/news/273400.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Mysql更新插入

在向表中插入數據的時候&#xff0c;經常遇到這樣的情況&#xff1a;1. 首先判斷數據是否存在&#xff1b; 2. 如果不存在&#xff0c;則插入&#xff1b;3.如果存在&#xff0c;則更新。 在 SQL Server 中可以這樣處理&#xff1a; if not exists (select 1 from t where id …

信息加密之信息摘要加密MD2、MD4、MD5

對于用戶數據的保密一直是各個互聯網企業頭疼的事&#xff0c;那如何防止用戶的個人信息泄露呢&#xff1f;今天為大家介紹一種最簡單的加密方式--信息摘要算法MD。它如何來保護用戶的個人信息呢&#xff1f;其實很簡單&#xff0c;當獲得到用戶的信息后&#xff0c;先對其進行…

Java 從網絡上下載文件

/*** 下載文件到本地 */public static void downloadPicture(String imageUrl, String filename){ URL url;try {url new URL(imageUrl);//打開網絡輸入流DataInputStream dis new DataInputStream(url.openStream());//建立一個新的文件FileOutputStream fos new FileOutp…

An error was encountered while running(Domain=LaunchSerivcesError, Code=0)

今天突然遇到這樣一個錯誤&#xff0c;編譯可以通過&#xff0c;但是運行就會彈出這個錯誤提示&#xff1a; An error was encountered while running(DomainLaunchSerivcesError, Code0) 解決辦法就是重置模擬器。 點擊模擬器菜單中的Reset Contents and Settings&#xff0c;…

hdu 4091 線性規劃

分析轉自&#xff1a;http://blog.csdn.net/dongdongzhang_/article/details/7955136 題意 &#xff1a; 背包能裝體積為N, 有兩種寶石&#xff0c; 數量無限&#xff0c; 不能切割。 分別為 size1 value 1 size2 value2 問背包能裝最大的價值&#xff1f; 思路 &#xff…

linux fmt命令

簡單的格式化文本 fmt [option] [file-list] fmt通過將所有非空白行的長度設置為幾乎相同&#xff0c;來進行簡單的文本格式化 參數 fmt從file-list中讀取文件&#xff0c;并將其內容的格式化版本發送到標準輸出。如果不制定文件名或者用連字符&#xff08;-&#xff09;來替代…

基于 jQuery支持移動觸摸設備的Lightbox插件

Swipebox是一款支持桌面、移動觸摸手機和平板電腦的jquery Lightbox插件。該lightbox插件支持手機的觸摸手勢&#xff0c;支持桌面電腦的鍵盤導航&#xff0c;并且支持視頻的播放。 在線預覽 源碼下載 簡要教程 Swipebox是一款支持桌面、移動觸摸手機和平板電腦的jQuery Ligh…

簡化工作——我的bat文件

重啟adb(radb.bat)&#xff1a; echo off call adb kill-server call adb start-server call adb remount push 一個apk(push.bat) echo off if "%1""launcher" ( call adb push 相關apk路徑 system/app )else ( echo 請添加一個參數!當前有效…

js操作數據庫

<script languagejavascript> function replace(v) { //容錯問題&#xff0c;請讀者自行進行判斷。 //定義SQL語句 var sql select * from Dictionary where MainID v ; //新建數據庫連接對象和數據集存取對象 var ConnDB new ActiveXObject(adodb.connection)…

Java中StringBuilder的清空方法比較

StringBuilder 沒有提供clear或empty方法。清空有3種方法&#xff1a;1&#xff09;新生成一個&#xff0c;舊的由系統自己主動回收2&#xff09;使用delete3&#xff09;使用setLength 將三種方法循環1000萬次&#xff0c;代碼&#xff1a; 1.public class sbbm { 2. 3. st…

LinkCutTree 總結

最近學習了LinkCutTree&#xff0c;總結一下。 LinkCutTree是一種數據結構&#xff08;是Tree Decomposition中的一種&#xff09;&#xff0c;她維護的一般是無向圖&#xff08;一個森林&#xff09;&#xff0c;支持連邊、刪邊、鏈修改、鏈查詢&#xff08;點屬于特殊的鏈&am…

linux 數據轉換

使用bc 可以進行不同進制之間的轉換 digit100; printf "the number is : %d\n" $digit;binary$( echo "obase2;$digit" | bc );printf "result is : %s\n" $binary;digit1$( echo "obase10;ibase2;$binary" | bc );printf "bina…

PHP常用的正則表達式(有些需要調整)

平時做網站經常要用正則表達式&#xff0c;下面是一些講解和例子&#xff0c;僅供大家參考和修改使用&#xff1a; "^\d$"  //非負整數&#xff08;正整數 0&#xff09; 順平注: 驗證輸入id數值&#xff0c;不能為0 $reg1/^[1-9]\d*$/; "^[0-9]*[1-9][0-9]…

浮點數據的運算

使用bc設置scale可以進行相應的浮點運算#!/bin/bash# FileName TestBc.shdigit100;sqrt$(echo "scale3;sqrt($digit) " | bc);echo $sqrt;var$(echo "scale3;10/3" | bc);echo $var;var1$( echo "scale2;0.5*3" | bc);echo $var1;

IE(IE6/IE7/IE8)支持HTML5標簽--20150216

讓IE&#xff08;ie6/ie7/ie8&#xff09;支持HTML5元素&#xff0c;我們需要在HTML頭部添加以下JavaScript&#xff0c;這是一個簡單的document.createElement聲明&#xff0c;利用條件注釋針對IE來調用這個js文件。Opera&#xff0c;FireFox等其他非IE瀏覽器就會忽視這段代碼…

linux shell 求絕對值

abs-1;printf "the number is : %d\n" $abs;printf "abs is : %d\n" $abs;if [ $abs -lt 0 ]; thenlet abs0-$abs;fiprintf "abs is : %d\n" $abs;

PyQt中從RAM新建QIcon對象 / Create a QIcon from binary data

一般&#xff0c;QIcon是通過png或ico等圖標文件來初始化的&#xff0c;但是如果圖標資源已經在內存里了&#xff0c;或者一個zip壓縮文件內&#xff0c;可以通過QPixmap作為橋梁&#xff0c;轉換為圖標。 zf zipfile.ZipFile("library.zip") # 準備zip文件 pm …

Java中的代碼塊標記

taga: {for (int k 0; k < 5; k) {System.out.println("kkkkkk: " k);if (k > 3) {break taga;}tagb: for (int i 0; i < 10; i) {System.out.println("i: " i);if (i 2) {break tagb;}}}}

windows中安裝zookeeper

Zookeeper 分布式服務框架是 Apache Hadoop 的一個子項目&#xff0c;它主要是用來解決分布式應用中經常遇到的一些數據管理問題&#xff0c;如&#xff1a;統一命名服務、狀態同步服務、集群管理、分布式應用配置項的管理等。本文將從使用者角度詳細介紹 Zookeeper 的安裝和配…

MySQL Event

一、前言自MySQL5.1.6起&#xff0c;增加了一個非常有特色的功能–事件調度器(Event Scheduler)&#xff0c;可以用做定時執行某些特定任務&#xff08;例如&#xff1a;刪除記錄、對數據進行匯總等等&#xff09;&#xff0c;來取代原先只能由操作系統的計劃任務來執行的工作。…