How to package an executable jar file
It’s clear that modern programming interfaces have made us lazier as professionals. It’s nothing new, in fact, it’s a good sign when a programmer is lazy; we prefer to work a little harder just once and then click a button the next n times we have to do the same task.
Nevertheless, a few days ago I found myself in the situation of having to package a few Java classes into an executable jar package. The problem was that I didn’t have my dear Eclipse handy and I had to do it “old school“, so I turned to my reliable document folder to find a few examples.
What follows is a description of the process for future reference, even though you can always turn to the always useful Java Tutorials for more information.
First: be clear about which files you need to package. For this little example it will only be one class which we will call “MyClass.class“. This was compiled from the “MyClass.java” source file, but that procedure is out of the scope of this article.
Second: create the manifest file. This file will tell the jar program which is the main class it needs to run. You can also indicate more things, like the classpath, etc. In our case the content of the manifest, which I will call MyClass.mf, is:
Manifest-Version: 1.0 Main-Class: MyClass
Third: run the jar command with the following syntax: jar cmf manifest_file target_file.jar content_1 content_2 content_3 content_n
Which translates to this in our example:
jar cmf MyClass.mf MyClass.jar MyClass.class
This will create the MyClass.jar file which we can execute as like this:
java -jar MyClass.jar
Or simply double-clicking it, if your system is set up to recognize jar files as executable.