Starting, Stopping and Querying services using Java

A Windows/Linux service could be stop and start using Java API. There are two version basically that do the job. Runtime class provides the old way to execute the OS commands that can be used for querying, stopping and starting the services.
For Java 1.5 onward you can also make use of ProcessBuilder class that gives you add-on for setting up the environment etc. before executing the OS command.
  • Old Style:
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(command);
  • Java 1.5 onward:
Process process = new ProcessBuilder(command).start();
  • You can use following commands for querying, starting and stopping the services:
// Audio Service in windows
String[] command = {"cmd.exe", "/c", "sc", "query", "STacSV"};
String[] command = {"cmd.exe", "/c", "sc", "start", "STacSV"};
String[] command = {"cmd.exe", "/c", "sc", "stop", "STacSV"};
  • A complete sample code:
import java.io.*;
import java.util.*;

public class Service {
  public static void main(String args[]) {
    // you can pass query/start/stop to respective 
    // operation on windows Audio Service while running
    String[] command = {"cmd.exe", "/c", "sc", args[0], "STacSV"};
    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);
    }
  }
}

Do you enjoy this article? please help spread the word. And if you don't, then let me know how I can improve it.

2 comments

Write comments
de
AUTHOR
Thu Sep 26, 08:03:00 PM GMT+5:30 delete

Very nice explanations with appropriate example.

prathap
java training in chennai

Reply
avatar
Tue Mar 17, 11:48:00 AM GMT+5:30 delete

Hi i have tried this but it doesn't work,
Soi have made little changes instead of using command "sc" i am using "net" and provide the service name and it started working
String[] command = {"cmd.exe", "/c", "net", "start", "Mobility Client"};

Reply
avatar