skip to main | skip to sidebar

Friday, July 15, 2011

Ant Script to make Executable JAR

Recently I observed search patterns about Ant script to make executable JAR files, many end up on wrong pages of my blog. This blog post is for those who are searching for it. Its fairly easy and simple to use Ant Script, to make an executable JAR file, see the script below.
<jar destfile="_dist/my-executable-jar.jar">
    <fileset dir="_bin" />
    …     <manifest>         <attribute name="Main-Class" value="com.mypackage.ClassWithMain" />     </manifest>
</jar>
As you can see, we usee the ‘jar’ ant task to create a JAR file, we want to create the JAR file with the name ‘my-executable-jar.jar’ – which is given as ‘destfile’ attribute value of ‘jar’ task and we wanted to include all the compiled classes which are available at ‘_bin’ directory – which is provided using ‘fileset’ tag in the second line of the script.
Then comes the important part – the ‘manifest’ tag. If you want to make a JAR file executable – you’ve to add a ‘Main-Class’ attribute to the MANIFEST file of your JAR file. As we wanted to specify an attribute of MANIFEST file – that is why the ‘manifest’ tag. In this tag we’ve a ‘attribute’ tag with ‘name’ and ‘value’ tag attributes. ‘name’ attribute says which attribute of the MANIFEST file you want to set and with which value, value is provided using ‘value’ attribute. In the above sample script we mentioned ‘Main-Class’ as attribute name and the value for this attribute as ‘com.mypackage.ClassWithMain’ – by this we are saying that the class which need to be used when we execute the JAR file is ‘com.mypackage.ClassWithMain’ [which means this class has the main() method and is the starting point for execution].
That is all – Happy Scripting :)

No comments:

Post a Comment