Ask Me Help Desk

Ask Me Help Desk (https://www.askmehelpdesk.com/forum.php)
-   Java (https://www.askmehelpdesk.com/forumdisplay.php?f=440)
-   -   How to Stop windows Service using Java (https://www.askmehelpdesk.com/showthread.php?t=353156)

  • May 12, 2009, 09:59 PM
    karianirav
    How to Stop windows Service using Java
    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...
  • May 26, 2009, 01:41 PM
    jstrike
    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.
  • Nov 16, 2009, 12:08 AM
    anilkumarbpl
    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();
    }
    }
    }
    }
  • Mar 8, 2011, 04:38 AM
    nwarkar
    Comment on jstrike's post
    Thank you it works for me.

  • All times are GMT -7. The time now is 10:25 PM.