Automatically including a file in your Java jar using Netbeans and Ant

First, a quick note of exposition.  If you’re eager just skip down to the header.

I started this site primarily because I started developing a Java program called Sprite Clipper that I wanted to share with other people.  I also knew it would be a learning experience (in more ways than I anticipated!), and I think maintaining a web presence outside of Facebook is desirable in its own right.

To track my program’s progress, I started to use git in conjunction with GitHub.  GitHub prominently displays a README file at the root of the project repository, which can be used for licensing info (BSD 3 clause in my case).  What I wanted to do was have this README file be automatically generated when I build the jar for my program using the same template text that I use for my new java classes, and also have the README included in the built jar.

Well, I fell pretty short of that goal.  I couldn’t find any information on how to invoke NetBeans’s templating engine, FreeMarker, from Ant without creating a stand-alone installation.  Since I had been working on this for a couple hours at this point, I decided to scale back my ambitions to simply copying a README file I made manually to the jar archive.  While it’s not a slick, sexy solution, it does accomplish what I wanted, albeit with less automation than I would have liked.

Copying a file into JAR archive

In your Netbeans project, go the file view on the left hand side and open up build.xml.  It should be at the top level of your directory.  Here you’ll see an XML file that has a lot of comments and only a little markup.  This is your Ant build script.  It’s kind of a like a makefile that’s specified in XML.

At the bottom of the file, insert the following just before the </project> tag at the end.

 <target name="-post-jar">
  <!-- Add the readme file to the jar archive -->
  <jar jarfile="${dist.jar}" update="true">
   <fileset dir="${basedir}" includes="README"/>

What this does is add the README file located in ${basedir} (the project’s root) to the jar file right after it’s made.  You’ll need to modify the fileset dir and includes properties to reflect the location of your own file that you want to copy into the jar.