从 java 启动 Windows 服务

2022-09-02 01:23:01

我们如何从Java启动/停止Windows服务?例如,我想从Java启动和停止mysql Windows服务。

如果启动/停止是可能的,那么是否有可能知道服务是否成功启动?


答案 1

您可以制定命令提示符脚本,以使用字符串数组启动、停止和检查服务的状态:

// start service
String[] script = {"cmd.exe", "/c", "sc", "start", SERVICE_NAME};

// stop service
String[] script = {"cmd.exe", "/c", "sc", "stop", SERVICE_NAME};

// check whether service is running or not
String[] script = {"cmd.exe", "/c", "sc", "query", APP_SERVICE_NAME, "|", "find", "/C", "\"RUNNING\""};

使用以下方法执行脚本:

Process process = Runtime.getRuntime().exec(script);

答案 2
import java.io.*;
import java.util.*;

public class ServiceStartStop {
    public static void main(String args[]) {
        String[] command = {"cmd.exe", "/c", "net", "start", "Mobility Client"};
        try {
            Process process = new ProcessBuilder(command).start();
            InputStream inputStream = process.getInputStream(); 
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
            }
        } catch(Exception ex) {
            System.out.println("Exception : "+ex);
        }
    }
}

它工作正常....而不是“sc”使用“net”命令。


推荐