Re: Java API to check status of Windows NT service?
The House Dawg wrote:
Can anyone share a code snippet written in java that takes the name of
a Windows NT service and returns the status of the service? Running,
Paused, Stopped, etc.
TIA,
Matt
Folks,
There's probably a million ways to do this, but I found the following
works well:
bool isServiceStopped ( String serviceName ) throws Exception
{
boolean serviceStopped = false;
/************************************************************
* Construct the command, putting quotes around the service *
* name in case the service name contains any blanks. *
************************************************************/
String command = "sc query " + "\"" + serviceName + "\"";
/*****************************************************************
* Execute the command and get a buffered reader for the output. *
*****************************************************************/
Process proc = Runtime.getRuntime ( ).exec ( command );
InputStream is = proc.getInputStream ( );
BufferedReader br = new BufferedReader ( new InputStreamReader (
is ) );
String line = null;
/*********************************************************************************
* Read the command output until the STATE token is found or EOF is
encountered. *
*********************************************************************************/
while ( ( line = br.readLine ( ) ) != null )
{
/********************************************
* Check if the STATE token has been found. *
********************************************/
if ( line.indexOf ( "STATE" ) > 0 )
{
/******************************************
* Check if the service STATE is STOPPED. *
******************************************/
if ( line.indexOf ( "STOPPED" ) > 0 )
{
serviceStopped = true;
}
break;
}
}
proc.waitFor ( );
/*****************************
* Cleanup system resources. *
*****************************/
is.close ( );
br.close ( );
return ( serviceStopped );
}