View Full Version : How to Stop windows Service using Java
karianirav
May 12, 2009, 09:59 PM
I want to Stop one of the windows service using java program, either using struts or using jsp...
Whenever I run my application it should stop the serivice and whenever I click on start in my program that service should be started...
Guide me through
Thanks in advance...
jstrike
May 26, 2009, 01:41 PM
Try something like this:
Process process = Runtime.getRuntime().exec("net stop myservice");
That will stop myservice on the computer that is running the java code. If it's on the same machine the user is on they will need the rights to start and stop that service.
anilkumarbpl
Nov 16, 2009, 12:08 AM
Try this:
import java.io.*;
public class MsWinSvc {
static final String CMD_START = "cmd /c net start \"";
static final String CMD_STOP = "cmd /c net stop \"";
public static int startService(String serviceName) throws Exception {
return execCmd(CMD_START + serviceName + "\"");
}
public static int stopService(String serviceName) throws Exception {
return execCmd(CMD_STOP + serviceName + "\"");
}
static int execCmd(String cmdLine) throws Exception {
Process process = Runtime.getRuntime().exec(cmdLine);
StreamPumper outPumper = new StreamPumper(process.getInputStream(), System.out);
StreamPumper errPumper = new StreamPumper(process.getErrorStream(), System.err);
outPumper.start();
errPumper.start();
process.waitFor();
outPumper.join();
errPumper.join();
return process.exitValue();
}
static class StreamPumper extends Thread {
private InputStream is;
private PrintStream os;
public StreamPumper(InputStream is, PrintStream os) {
this.is = is;
this.os = os;
}
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null)
os.println(line);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
nwarkar
Mar 8, 2011, 04:38 AM
Thank you it works for me.