获取windows的服务,启动服务,停止服务。
package notion.install.busi.check;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import notion.install.vo.ServiceVO;
import notion.vo.pub.exception.BusinessException;
/**
* 系统服务业务类
* @author ganxz
* @date 2012-10-29
*/
public class SysServicesBusi {
/**
* 获取系统服务列表
* @return
* @throws BusinessException
*/
public List<ServiceVO> getSysServiceList() throws BusinessException{
BufferedReader bufferedReader = null;
Process proc = null;
try {
proc = Runtime.getRuntime().exec("sc query state= all");
bufferedReader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = "";
List<ServiceVO> rtnLst = new ArrayList<ServiceVO>();
ServiceVO srcvo = null;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
if(!line.equals("") && line.indexOf(":") >=0){
String tmpstr = line.substring(0,line.indexOf(":")).trim();
String tmpvalue = line.substring(line.indexOf(":") + 1).trim();
if(tmpstr.equals("SERVICE_NAME")){
srcvo = new ServiceVO();
srcvo.setService_name(tmpvalue);
rtnLst.add(srcvo);
}else if(tmpstr.equals("DISPLAY_NAME")){
srcvo.setDisplay_name(tmpvalue);
}else if(tmpstr.equals("TYPE")){
srcvo.setType(tmpvalue);
}else if(tmpstr.equals("STATE")){
if(tmpvalue.contains("STOPPED")){
srcvo.setState(1);
}else if(tmpvalue.contains("RUNNING")){
srcvo.setState(4);
}
}
}
}
for(ServiceVO src :rtnLst){
System.out.println(src.getService_name() + ":" + src.getDisplay_name()+ ":" + src.getState());
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (Exception ex) {
}
}
if (proc != null) {
try {
proc.destroy();
} catch (Exception ex) {
}
}
}
return null;
}
/**
* 启动服务
* @param service_name
* @throws BusinessException
*/
public void startService(String service_name) throws BusinessException{
try {
Runtime.getRuntime().exec("net start " + service_name);
} catch (IOException e) {
throw new BusinessException("启动系统服务异常!原因:",e);
}
}
/**
* 关闭服务
* @param service_name
* @throws BusinessException
*/
public void stopService(String service_name) throws BusinessException{
try {
Runtime.getRuntime().exec("net stop " + service_name);
} catch (IOException e) {
throw new BusinessException("停止系统服务异常!原因:",e);
}
}
public static void main(String[] args) {
try {
new SysServicesBusi().startService("aaa");
} catch (BusinessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}