javaantbuild

How to include an external jar lib in my Ant build


I have the following build.xml:

<project>

<target name="clean">
    <delete dir="./build"/>
</target>

<target name="compile">
    <mkdir dir="./build/classes"/>          
    <javac srcdir="./src" destdir="./build/classes"/>                   
</target>

<target name="jar">
    <mkdir dir="./build/jar"/>
    <jar destfile="./build/jar/DependencyFinder.jar" basedir="./build/classes">
        <manifest>
            <attribute name="DependencyFinder" value="main"/>
        </manifest>
    </jar>
</target>

<target name="run">
    <java jar="./build/jar/DependencyFinder.jar" classname="${main-class}" fork="true"/>                    
</target>

</project>

Here is my directory structure:

/build /lib /MagicFolder /Src /build.xml

Folder src contains .java files.

Path to MagicFolder should be an input parameter.

lib has external .jar library which should be included in my build.

build folder which will have compiled .jar and.class` files

QUESTION: How should I change my build.xml? My build.xml should:

  1. Add external lib ./lib/jbl.jar
  2. When I run my application put 2 input parametrs for my application

Solution

  • If you need to add a jar to classpath to compile the code (sorry, it isn't quite clear what you're asking for), then you need to change <javac> task to look like this:

    <javac srcdir="./src" destdir="./build/classes">   
        <classpath>
            <pathelement path="lib/jbl.jar"/>
        </classpath>
    </javac>
    

    Or if you need to add contents of jbl.jar to the jar you are creating, then you need to change your <jar> task to look like this:

    <jar destfile="./build/jar/DependencyFinder.jar" basedir="./build/classes>
        <zipgroupfileset dir="lib" includes="jbl.jar" />
        <manifest>
            <attribute name="DependencyFinder" value="main"/>
            <attribute name="Main-Class" value="org.ivanovpavel.YourMainClass"/>
        </manifest>
    </jar>
    

    To add arguments to <java> call, use nested <arg> elements:

    <target name="run">
        <java jar="./build/jar/DependencyFinder.jar:lib/jbl.jar" classname="dependencyfinder.DependencyFinder">  
            <arg value="Alexander Rosenbaum"/>
            <arg value="Dmitry Malikov"/>
        </java>                  
    </target>