start windows service from java

后端 未结 5 1365
粉色の甜心
粉色の甜心 2020-12-13 07:05

How can we start/stop a Windows Service from Java? For example, I would like to start and stop the mysql Windows Service from Java.

If start/stop is possible, then i

相关标签:
5条回答
  • 2020-12-13 07:36

    You can formulate a Command Prompt script to start, stop, and check status on a service using a String Array:

    // 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\""};
    

    Execute scripts using the following:

    Process process = Runtime.getRuntime().exec(script);
    
    0 讨论(0)
  • 2020-12-13 07:37
    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);
            }
        }
    }
    

    It worked fine .... instead of "sc" use "net" command.

    0 讨论(0)
  • 2020-12-13 07:38

    You can execute system commands from java using the exec () command - A simple tutorial on the same can be found here - http://www.java-samples.com/showtutorial.php?tutorialid=8

    Now you can use the system commands to start / stop windows services - A sample of the same can be found here

    http://www.windowsitpro.com/article/registry2/how-can-i-stop-and-start-services-from-the-command-line-

    I am not very sure about monitoring the status , so can't be of much help in that regards

    0 讨论(0)
  • 2020-12-13 07:39

    You may execute following commands via Runtime#exec method.

    net start and net stop (full information is available at : http://technet.microsoft.com/en-us/library/cc736564%28WS.10%29.aspx)

    Probably you will have to use cmd /c net start as it would execute the command under shell.

    0 讨论(0)
  • 2020-12-13 07:42

    Did you try JNA? It has some good api to do this.

    JNA is very active in SO - you could come back here with specific questions.

    0 讨论(0)
提交回复
热议问题