Demo 3: Build and create a Window NT Service
Function: Convert JAR archive into Executive.
Part 1: Build a java program and create a jar charchive
1. Compose a java program D:\test\HelloService.java:
The function of the demo service: Listen on a port (for example 1234). Create a new thread when a client connects. Then, the service thread will echo back whatever the client send, until 'q' to to stop serve:
package test;
import java.io.*;
import java.net.*;
public class HelloService implements Runnable
{
// socket
private Socket m_sock;
// Constructor
public HelloService(Socket sock)
{
m_sock = sock;
}
// Runnable method
public void run()
{
try
{
BufferedReader in = new BufferedReader(
new InputStreamReader(m_sock.getInputStream())
);
PrintWriter out = new PrintWriter(
m_sock.getOutputStream()
);
// welcome
out.println("---- Welcome! Type 'q' to EXIT: ----");
out.flush();
// echo back until 'q'
String line;
while( (line = in.readLine()) != null )
{
if( line.equalsIgnoreCase("q") )
break;
out.println(line);
out.println();
out.flush();
}
// close socket and exit this thread
m_sock.close();
}
catch(Exception e)
{
e.printStackTrace(System.err);
}
}
public static void main(String[] args) throws Exception
{
// listen: 1234
ServerSocket listen = new ServerSocket(1234);
while(true)
{
// accept
Socket socket = listen.accept();
// open thread to serve
Thread thread = new Thread(new HelloService(socket));
thread.start();
}
}
} |
2. Compile, we get HelloService.class:
D:\>javac -target 1.2 test/HelloService.java |
3. Use jar.exe to create service.jar:
D:\>jar cvf service.jar test/HelloService.class |
Part 2: Use tool to create .exe file
1. Download and install this free tool:
[Free Edition Download]
2. Select the jar file, then press next to continue:

3. Select the application type. Here "Windows NT Service":

4. Input the main class to start and the service name:

5. Type in the exe filename you want to get:

6. Press next, the exe file is generated.
Part 3: Run the Exe file
1. Windows NT Service installation and startup:

2. Use the service. Let's us telnet:
D:\>telnet localhost 1234 |

3. Service stop and uninstallation:

4. Test the service program on console:

The service is running, and can be tested by telnet equally.
5. Download the program and result exe in this demo:
[service.zip] - 15kb
More Demos:
Demo 1: How to generate a CONSOLE application in java?
Demo 2: How to generate a Windows GUI application in java?
Demo 4: Window NT Service supports PAUSE/CONTINUE.
Demo 5: System Taskbar Tray Icon and Event Log
|