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:

 

<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/HelloWorld.jar" basedir="build/classes">

            <manifest>

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

            </manifest>

        </jar>

    </target>

 

    <target name="run">

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

    </target>

 

</project>

 

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:

 

java-only

Ant

md build\classes

javac

    -sourcepath src

    -d build\classes

    src\oata\HelloWorld.java

echo Main-Class: oata.HelloWorld>mf

md build\jar

jar cfm

    build\jar\HelloWorld.jar

    mf

    -C build\classes

    .

 

 

 

java -jar build\jar\HelloWorld.jar

 

<mkdir dir="build/classes"/>

<javac

    srcdir="src"

    destdir="build/classes"/>

<!-- automatically detected -->

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

<mkdir dir="build/jar"/>

<jar

    destfile="build/jar/HelloWorld.jar"

 

    basedir="build/classes">

    <manifest>

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

    </manifest>

</jar>

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

 

 

 


 Ant 1 | Back to Main | Ant 3