How to Build a Self Executable Jar File
I’m always looking for ways to simplify the management of Java services. Recently, I’ve learned how to create a self-executing jar file without the need for an extra bash script. Having one file helps when you’re handing off your service to be deployed by opsy folks. Here’s how.
Create a main class. For this post, the ubiquitous Hello World:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
Create a manifest file which defines your main class:
$ echo Main-Class: HelloWorld > MANIFEST.MF
Next, compile your class(es):
javac HelloWorld.java
Assemble a jar file:
java -cvmf MANIFEST.MF hello.jar HelloWorld.class
Create a small bash script to execute the jar (stub.sh
):
#!/usr/bin/java -jar
You can optionally also include JAVA_OPTS in this bash script:
#!/usr/bin/java -Xms256m -Xmx512m -jar
Finally, munge the bash script and jar together into a new file:
cat stub.sh hello.jar > hello.sh
Make the file executable:
chmod +x hello.sh
Now you can execute the file:
./hello.sh