天天看點

java檢測Windows服務(NT服務)是否安裝、啟動

        之前項目寫的Windows服務需要內建到B/S架構系統中去,友善使用者的操作。用到的函數是Runtime.getRuntime().exec()。

        實作如下:

Process process = Runtime.getRuntime().exec("sc query AzureStorageService");//查詢服務是否安裝
InputStream inputStream = process.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"GBK"));//注意中文編碼問題
String temp = "",result="";
while ((temp=bufferedReader.readLine())!=null){
	result += temp;
}//result結果中判斷服務是否存在
bufferedReader.close();
inputStream.close();
           
Process process = Runtime.getRuntime().exec("tasklist /svc");//列出服務清單判斷服務是否啟動
String temp = "",result="";
InputStream inputStream = process.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"GBK"));//注意中文編碼問題
while ((temp=bufferedReader.readLine())!=null){
	result += temp;
}
bufferedReader.close();
inputStream.close();
           

        直接執行.bat檔案

String path = ServletActionContext.getRequest().getSession().getServletContext().getRealPath("/");
String command = path + "startup.bat";
Process process  = Runtime.getRuntime().exec(command,null,new File(path));//到指定目錄執行
InputStream inputStream = process.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"GBK"));//注意中文編碼問題
String temp = "",result="";
while ((temp=bufferedReader.readLine())!=null){
	result += temp;
}
bufferedReader.close();
inputStream.close();