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.
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); } } }
2 comments
Write commentsVery nice explanations with appropriate example.
Replyprathap
java training in chennai
Hi i have tried this but it doesn't work,
ReplySoi 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"};
Emoticon Emoticon