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 is it possible to know whether the service is started successfully or not?
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With