使用Java控制Windows服务的一个工具类
- 提供获取windows系统服务的运行状态获取
- 提供重启windows服务的方法
代码如下:
import java.io.*;
import java.nio.charset.Charset;
/**
* Windows系统工具类
*
* @author Zaki Chen
*/
public class WindowsServiceTool {
private WindowsServiceTool() {
}
/**
* 获取windows服务实例对象
*
* @param serviceName
* @return
*/
public static WindowsService getService(String serviceName) {
return new WindowsService(serviceName, Charset.defaultCharset());
}
/**
* 获取windows服务实例对象
*
* @param serviceName
* @param charset windows命令执行输出流字符集
* @return
*/
public static WindowsService getService(String serviceName, Charset charset) {
return new WindowsService(serviceName, charset);
}
/**
* 获取windows服务实例对象
*
* @param serviceName
* @param charset windows命令执行输出流字符集
* @return
*/
public static WindowsService getService(String serviceName, String charset) {
return new WindowsService(serviceName, Charset.forName(charset));
}
/**
* 读取输入流中的文本信息
*
* @param input 文本输入流
* @param charset 文本编码
* @return
*/
private static String convertInputStream2Str(InputStream input, Charset charset) {
final char[] buffer = new char[4096];
final StringBuilder out = new StringBuilder();
try {
final Reader in = new InputStreamReader(input, charset);
try {
for (; ; ) {
int rsz = in.read(buffer, 0, buffer.length);
if (rsz < 0) {
break;
}
out.append(buffer, 0, rsz);
}
} finally {
in.close();
}
} catch (UnsupportedEncodingException ex) {
/* ... */
} catch (IOException ex) {
/* ... */
}
return out.toString();
}
public static class WindowsService {
/**
* 服务名称
*/
private String serviceName;
/**
* 服务是否存在
*/
private boolean isExists;
/**
* 服务运行状态
*/
private ServiceState runningStatus;
/**
* 服务信息
*/
private String info;
/**
* windows状态码服务_运行中
*/
private final static String SERVICE_RUNNING_CODE = "4";
/**
* windows状态码服务_正在停止运行
*/
private final static String SERVICE_STOPPING_CODE = "3";
/**
* windows状态码服务_已停止运行
*/
private final static String SERVICE_STOPPED_CODE = "1";
/**
* windows操作系统cmd指令返回内容的字符集
*/
private Charset charset;
/**
* 直接完成状态的初始化
*
* @param serviceName
*/
public WindowsService(String serviceName, Charset charset) {
this.serviceName = serviceName;
this.charset = charset;
Runtime runtime = Runtime.getRuntime();
String result;
try {
Process process = runtime.exec("sc query " + serviceName);
InputStream inputStream = process.getInputStream();
result = convertInputStream2Str(inputStream, Charset.defaultCharset());
} catch (IOException e) {
e.printStackTrace();
//TODO 日志信息处理
isExists = false;
runningStatus = ServiceState.UNKNOWN;
info = null;
return;
}
String[] split = result.split("\n");
if (split.length < 5) {
isExists = false;
runningStatus = ServiceState.UNKNOWN;
info = null;
return;
}
isExists = true;
String state = split[3].split(":")[1].trim();
String code = state.substring(0, 1);
info = state.substring(3);
if (SERVICE_RUNNING_CODE.equals(code)) {
runningStatus = ServiceState.RUNNING;
} else if (SERVICE_STOPPING_CODE.equals(code)) {
runningStatus = ServiceState.STOPPING;
} else if (SERVICE_STOPPED_CODE.equals(code)) {
runningStatus = ServiceState.STOPPED;
} else {
runningStatus = ServiceState.UNKNOWN;
}
}
// /**
// * 重启服务
// *
// * @return 执行结果
// */
// public boolean restartService() throws Exception {
// if (!isExists) {
// return false;
// }
// boolean isStop = false;
// if (getRunningStatus() == ServiceState.RUNNING) {
// isStop = stopService();
// }
// if (isStop) {
// boolean isStart = startService();
// if (isStart) {
// return true;
// }
// }
// return false;
// }
/**
* 启动服务
*
* @return 执行结果
*/
public boolean startService() throws Exception {
if (!isExists) {
return false;
}
boolean ret = false;
if (getRunningStatus() == ServiceState.STOPPED) {
try {
Process exec = Runtime.getRuntime().exec("net start " + serviceName);
InputStream errorStream = exec.getErrorStream();
String errMsg = convertInputStream2Str(errorStream, getCharset());
if (errMsg != null && !"".equals(errMsg)) {
throw new Exception("执行启动服务[" + getServiceName() + "]出错:\n" + errMsg);
}
runningStatus = ServiceState.RUNNING;
ret = true;
} catch (IOException e) {
e.printStackTrace();
}
}
return ret;
}
/**
* 停止服务
*
* @return 执行结果
*/
public boolean stopService() throws Exception {
if (!isExists) {
return false;
}
boolean ret = false;
if (getRunningStatus() == ServiceState.RUNNING) {
try {
Process exec = Runtime.getRuntime().exec("net stop " + serviceName);
InputStream errorStream = exec.getErrorStream();
String errMsg = convertInputStream2Str(errorStream, getCharset());
if (errMsg != null && !"".equals(errMsg)) {
throw new Exception("执行停止服务[" + getServiceName() + "]出错:\n" + errMsg);
}
runningStatus = ServiceState.STOPPED;
ret = true;
} catch (IOException e) {
e.printStackTrace();
}
}
return ret;
}
private enum ServiceState {
/**
* 正在运行
*/
RUNNING,
/**
* 正在停止
*/
STOPPING,
/**
* 已停止
*/
STOPPED,
/**
* 未知(服务不存在)
*/
UNKNOWN
}
/**
* 服务名
*
* @return
*/
public String getServiceName() {
return serviceName;
}
/**
* 服务是否存在
*
* @return
*/
public boolean isExists() {
return isExists;
}
/**
* 服务运行状态
*
* @return
*/
public ServiceState getRunningStatus() {
return runningStatus;
}
/**
* 服务信息
*
* @return
*/
public String getInfo() {
return info;
}
public Charset getCharset() {
return charset;
}
@Override
public String toString() {
return "WindowsService{" +
"serviceName='" + serviceName + '\'' +
", isExists=" + isExists +
", runningStatus=" + runningStatus +
", info='" + info + '\'' +
'}';
}
}
/**
* 简单测试
* @param args
*/
public static void main(String[] args) {
WindowsServiceTool.WindowsService windowsService = WindowsServiceTool.getService("MySQL_5.7_3307", "GBK");
System.out.println(windowsService);
try {
windowsService.stopService();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("停止服务后 - > " + windowsService);
try {
windowsService.startService();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("再次启动服务后 -> " + windowsService);
}
}