Java - How to create a Jar file in an Ant target

Here’s an example of an Ant target that creates a jar file. This Ant target creates a jar file for a Java Swing application I’ve created named “WikiTeX.”

Here’s the source code for my Ant target:

<!-- create-jar target -->
<target name="create-jar" depends="compile">
  <copy todir="classes/com/devdaily/opensource/wikitex/view">
    <fileset dir="helpfiles">
      <include name="**/*.*"/>
    </fileset>
  </copy>
  <jar basedir="classes" jarfile="release/wikitex.jar" manifest="resources/wikitex.manifest"/>
  <copy todir="release">
    <fileset dir="lib">
      <include name="**/*.jar"/>
      <include name="**/*.zip"/>
    </fileset>
  </copy>
</target>

Discussion

Here’s a description of what this Ant target does:

  1. The target is named create-jar, and it depends on another target named compile.
  2. In the first copy task, I’m copying a collection of help-related files to a subdirectory of the classes folder, which is where all my compiled classes are located.
  3. Next, the Ant jar task creates a jar file named wikitex.jar in a directory named release, including all the files from the classes directory, and the manifest file shown.
  4. In the second copy task, I copy all the jar and zip files in the lib directory to the release directory.

The end result of this Ant target is that the jar file for my application, and all the jar files it depends on, are placed into a directory named release.