从 Java 应用程序中查找 Windows 服务的状态?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5388888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 10:53:51  来源:igfitidea点击:

Find status of Windows service from Java application?

javawindows-services

提问by Indranil Ghosh

How to check the status of the windows services from a java program?

如何从java程序检查windows服务的状态?

回答by Waleed

on the following example you can find how can you check windws service status and you can parsed to do certain action

在以下示例中,您可以找到如何检查windws 服务状态,并且您可以解析以执行某些操作

import java.util.*;
import java.sql.*;
import java.io.*;
import java.text.*;
public class doscmd 
 { 
    public static void main(String args[]) 
      { 
        try 
         { 
           Process p=Runtime.getRuntime().exec("sc query browser"); 

BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream())); 

           String line=reader.readLine();
           while(line!=null) 
            { 
              if(line.trim().startsWith("STATE"))

               {

                if (line.trim().substring(line.trim().indexOf(":")+1,line.trim().indexOf(":")+4).trim().equals("1"))
    System.out.println("Stopped");
else
    if (line.trim().substring(line.trim().indexOf(":")+1,line.trim().indexOf(":")+4).trim().equals("2"))
        System.out.println("Startting....");
    else
        if (line.trim().substring(line.trim().indexOf(":")+1,line.trim().indexOf(":")+4).trim().equals("3"))
            System.out.println("Stopping....");
        else
            if (line.trim().substring(line.trim().indexOf(":")+1,line.trim().indexOf(":")+4).trim().equals("4"))
                System.out.println("Running");

  }
   line=reader.readLine(); 
   } 

 } 

 catch(IOException e1) { } 



   } 
 } 

回答by Jim Garrison

At the very least you should be able to launch a cmd.exe process with the command sc query service-nameand parse the output to determine the status. Not pretty, but lacking a Java API to the Windows service manager this would be a viable alternative.

至少您应该能够使用该命令启动 cmd.exe 进程sc query service-name并解析输出以确定状态。不漂亮,但缺少 Windows 服务管理器的 Java API,这将是一个可行的替代方案。

EDIT - Read the Javadoc for java.lang.ProcessBuilder, which will allow you to execute an external command. You should probably set the redirectErrorStreamproperty so that you don't have to handle two input streams (stdout and stderr), making for a much simpler design.

编辑 - 阅读java.lang.ProcessBuilder的 Javadoc ,这将允许您执行外部命令。您可能应该设置redirectErrorStream属性,这样您就不必处理两个输入流(stdout 和 stderr),从而使设计更加简单。