Ant: Java Hello World in Ant

This is the third part of the so called Ant series I have been writing in this blog, about Apache Ant. This post is mainly about building and running a Java program using Ant. In the example I’m using here, its a Hello World program in simple Java, but most of these basic Ant steps would be same for any other Java program you might run.

The previous posts on Ant can be found here:

  1. Apache Ant
  2. Ant: Installation
  3. Ant: Hello World in Ant

Java Program

Create the following simple program and save it as in a sub folder src:

public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World");

Ant Script

Use a text editor to create a file called build.xml and place it in the main folder:

<?xml version="1.0" encoding="UTF-8"?>
<project name="Run Test" default="run" basedir=".">

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

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

<target name="jar" depends="compile">
<mkdir dir="build/jar"/>
<jar destfile="build/jar/HelloWorld.jar"
<attribute name="Main-Class" value="HelloWorld"/>

<target name="run" depends="jar">
<java jar="build/jar/HelloWorld.jar" fork="true"/>



Run ant in command line:

[root@nimal ant-hw]# ant
Buildfile: build.xml

[delete] Deleting directory /opt/ant-hw/build

[mkdir] Created dir: /opt/ant-hw/build/classes
[javac] Warning: modified in the future.
[javac] Compiling 1 source file to /opt/ant-hw/build/classes

[mkdir] Created dir: /opt/ant-hw/build/jar
[jar] Building jar: /opt/ant-hw/build/jar/HelloWorld.jar

[java] Hello World
Total time: 4 seconds

Enhance the build file

Now we have a working buildfile we could do some enhancements: many time you are referencing the same directories, main-class and jar-name are hard coded, and while invocation you have to remember the right order of build steps.

<project name="HelloWorld" basedir="." default="main">

<property name="src.dir" value="src"/>
<property name="build.dir" value="build"/>
<property name="classes.dir" value="${build.dir}/classes"/>
<property name="jar.dir" value="${build.dir}/jar"/>
<property name="main-class" value="HelloWorld"/>
<target name="clean">
<delete dir="${build.dir}"/>

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

<target name="jar" depends="compile">
<mkdir dir="${jar.dir}"/>
<jar destfile="${jar.dir}/${}.jar"
<attribute name="Main-Class" value="${main-class}"/>

<target name="run" depends="jar">
<java jar="${jar.dir}/${}.jar" fork="true"/>

<target name="clean-build" depends="clean,jar"/>

<target name="main" depends="clean,run"/>


Feedback and questions are welcome via comment or you can email me at talkout AT SPAMFREE gmail DOT com

Leave a Reply