Adventures of a Geek various programming related articles

27Feb/100

How to make executable jar files using ant

Executable jar files are useful as they allow you to run a java application by clicking on the .jar icon.

Ant is a software tool for automating software build processes. It can also be used to compile/run java programs. I will show you how to use it to make a jar file.

To use ant, you need to install it, create a "build.xml" file and run the file using the "ant" command in the console.

To make a jar file executable, you have to include the .class files of your application, define the main class of the application and, maybe, set the classpath for running your application. A file called "manifest.mf" has to be included in the jar file in order to define the main class and classpath.

The "manifest.mf" file looks similar to this:

Manifest-Version: 1.0
Ant-Version: Apache Ant 1.7.1
Created-By: 14.3-b01 (Sun Microsystems Inc.)
Main-Class: MyClass
Class-Path: .

As you can see, it defines the main class "MyClass" and the classpath "." (current directory).

I will now show you the "build.xml" file needed to create a "manifest.mf" file and create the executable jar using this manifest file.

The file looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<project name="MyProject" default="jar" basedir=".">
    <target name = "jar">
        <delete file = "MyJar.jar"/>
        <delete file = "MANIFEST.MF"/>
        <manifest file = "MANIFEST.MF">
            <attribute name = "Main-Class" value = "MyClass"/>
            <attribute name = "Class-Path" value = "."/>
        </manifest>
        <jar destfile = "MyJar.jar" basedir = "." includes = "*.class"  manifest = "MANIFEST.MF"/>
   </target>
</project>

First, we delete the "MyJar.jar" file and the "manifest.mf" file if they already exist:

<delete file = "MyJar.jar"/>
<delete file = "MANIFEST.MF"/>

After that, we create the new manifest file setting the main class and the classpath:

<manifest file = "MANIFEST.MF">
    <attribute name = "Main-Class" value = "MyClass"/>
   <attribute name = "Class-Path" value = "."/>
</manifest>

And finally, we create the jar file including all the .class files in the current directory and using the “manifest.mf” file we just created:

<jar destfile = 'MyJar.jar' basedir = '.' includes = '*.class' manifest = 'MANIFEST.MF'/>

After running the project with ant, a MyJar,jar file will appear in the current folder. This can be used to run your application.

Tagged as: , , No Comments