Creating JAR Files

The jar task JARs files for you. Example 3-4 is a fairly complex example, which creates a new JAR file with an included manifest, MANIFEST.MF, that contains several attributes.

Example 3-4. Using the jar task (ch03/jar/build.xml)

<?xml version="1.0" ?>
<project default="main">

    <property name="message" value="Building the .jar file." />
    <property name="src" location="source" />
    <property name="output" location="bin" />

    <target name="main" depends="init, compile, compress">
        <echo>
            ${message}
        </echo>
    </target>
  
    <target name="init">
        <mkdir dir="${output}" />
    </target>
  
    <target name="compile">
        <javac srcdir="${src}" destdir="${output}" />
    </target>
  
    <target name="compress">
        <jar destfile="${output}/Project.jar" basedir="${output}" 
            includes="*.class" >
            <manifest>
                <attribute name="Author" value="${user.name}"/>
                <section name="Shared">
                    <attribute name="Title" value="Example"/>
                    <attribute name="Vendor" value="MegaAntCo"/>
                </section>
                <section name="Copyright">
                    <attribute name="Copy" value="(C) MegaAntCo 2005"/>
                </section>
            </manifest>
        </jar>
    </target>
</project>

The created JAR file contains Project.class and MANIFEST.MF; this latter file contains these contents:

Manifest-Version: 1.0
Ant-Version: Apache Ant 1.6.1
Created-By: 1.4.2_03-b02 (Sun Microsystems Inc.)
Author: Steven Holzner

Name: Shared
Title: Example
Vendor: MegaAntCo

Name: Copyright
Copy: (C) MegaAntCo 2005

Tip

Want to sign your JAR file for distribution? Use the jarsign task like this:

<signjar jar="jarfile.jar" alias="development" ...

Get Ant: The Definitive Guide, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.