Hands-on Tutorial: Hello World with Ant 2

(On Windows system)





Four steps to a running application


After finishing the java-only step we have to think about our build process. We have to compile our code; otherwise we couldn't start the program. Oh - "start" - yes, we could provide a target for that. We should package our application. Now it's only one class - but if you want to provide a download, no one would download several hundred files ... (think about a complex Swing GUI) - so let us create a jar file. A startable or runnable jar file would be nice ... And it's a good practice to have a "clean" target, which deletes all the generated stuff. Many failures could be solved just by a "clean build".

By default Ant uses build.xml as the name for a buildfile, so our .\build.xml would be:




    <target name="clean">

        <delete dir="build"/>



    <target name="compile">

        <mkdir dir="build/classes"/>

        <javac srcdir="src" destdir="build/classes"/>



    <target name="jar">

        <mkdir dir="build/jar"/>

        <jar destfile="build/jar/HelloWorld.jar" basedir="build/classes">


                <attribute name="Main-Class" value="oata.HelloWorld"/>





    <target name="run">

        <java jar="build/jar/HelloWorld.jar" fork="true"/>








The build.xml file content



The physical path for build file


Create the build.xml file and place it same level as src folder. Now you can compile, package and run the application via


C:\>myantexercise>ant compile

C:\>myantexercise>ant jar

C:\>myantexercise>ant run


Compiling Java source code using Ant





Creating JAR file using Ant tool


Running Java JAR file using Ant tool





Or shorter with


C:\>myantexercise>ant compile jar run


Your task:


Find a solution for the following output 'error' as seen in the console output


Unable to locate tools.jar. Expected to find it in C:\Program Files\Java\jre6\lib\tools.jar


While having a look at the buildfile, we will see some similar steps between Ant and the java-only commands:




md build\classes


    -sourcepath src

    -d build\classes


echo Main-Class: oata.HelloWorld>mf

md build\jar

jar cfm



    -C build\classes





java -jar build\jar\HelloWorld.jar


<mkdir dir="build/classes"/>




<!-- automatically detected -->

<!-- obsolete; done via manifest tag -->

<mkdir dir="build/jar"/>






        <attribute name="Main-Class" value="oata.HelloWorld"/>



<java jar="build/jar/HelloWorld.jar" fork="true"/>






 Ant 1 | Back to Main | Ant 3