Throughout this Ant tutorial, I will walk you through the process of developing a Java project using Ant build, step by step. After finishing this lesson, you will be able to wrote Ant script for a standard build of a Java project. And based on that, you will be able to modify Ant build script of an existing project and customize the build process when needed.

To follow this tutorial, please use a text editor (Textpad or Sublime) with Command line prompt (on Windows) or Terminal (on Linux).

 

1. Download and setup Apache Ant

Go to https://ant.apache.org/bindownload.cgi to download the latest binary distribution of Apache Ant.

When I’m writing this, the latest release is Ant 1.10.7 which requires minimum of Java 8 at runtime. Download the apache-ant-1.10.7-bin.zip file and extract it on your hard drive. Then update the system environment variable PATH to include a path to apache-ant-1.10.7\bin directory. On Windows, you can type the following command in a Command Prompt window launched with administrator privilege:

setx -m PATH "%PATH%;apache-ant-1.10.8\bin"
Then open another command prompt, type ant -version and hit Enter. You should see the following output:

ant-version

That means Apache Ant was installed successfully and ready to be used.

 

2. Code Java Project



We will code a Java program that inserts some contact information to a MySQL database. So create a new database schema named contactsdb with one table contact by executing the following MySQL statements (using either MySQL Workbench or MySQL Command Line Client):

CREATE DATABASE `contactsdb`;
CREATE TABLE `contacts` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `firstname` varchar(20) NOT NULL,
  `lastname` varchar(20) NOT NULL,
  `city` varchar(30) NOT NULL,
  `country` varchar(30) NOT NULL,
  PRIMARY KEY (`id`)
);
As you can see, the contacts table has 5 columns: id, firstname, lastname, city, and country.

Next, make a new directory for the project, called ContactManager. And under this project create src folder to store Java source files. And create the directory com\mycompany under src, for the package named com.mycompany. Then we have the following directory structure:

project-structure

Now under mycompany, create a new Java source file named ContactInserter.java with the following code:

package com.mycompany;

import java.sql.*;

public class ContactInserter {
	public static void main(String[] args) {
		String url = "jdbc:mysql://localhost:3306/contactsdb?useSSL=false";
		String username = "root";
		String password = "password";
		String sql = "INSERT INTO contacts (firstname, lastname, city, country) VALUES (?, ?, ?, ?)";

		try {

			Connection connection = DriverManager.getConnection(url, username, password);
			PreparedStatement statement = connection.prepareStatement(sql);

			statement.setString(1, "Tom");
			statement.setString(2, "Eagar");
			statement.setString(3, "Chicago");
			statement.setString(4, "U.S.A");

			int rows = statement.executeUpdate();

			if (rows > 0) {
				System.out.println("A row was inserted.");
			} else {
				System.out.println("No row was inserted.");
			}

			connection.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}
}
As you can see, this program simply connects to the database, inserts a row to the contacts table and then exits.

Next, you will see how to use Ant to compile, package and run this program.

 

3. Write Ant build script

Create the build.xml file under project’s root directory with the following XML code:

<project name="ContactProject" default="dist" basedir=".">

  <property name="src" location="src"/>
  <property name="build" location="build"/>
  <property name="dist" location="dist"/>

  <target name="init">
    <tstamp/>
    <mkdir dir="${build}"/>
  </target>

  <target name="compile" depends="init" description="compile the source">
    <javac srcdir="${src}" destdir="${build}"/>
  </target>

  <target name="dist" depends="compile" description="generate the distribution">
    <mkdir dir="${dist}"/>

    <jar jarfile="${dist}/ContactManager-${DSTAMP}.jar" basedir="${build}">
            <manifest>
                <attribute name="Main-Class" value="com.mycompany.ContactInserter"/>
            </manifest>    
    </jar>
  </target>

  <target name="clean" description="clean up">
    <delete dir="${build}"/>
    <delete dir="${dist}"/>
  </target>
</project>
This Ant build file contains 4 targets init, compile, dist and clean – similar to the one described in the previous lesson.

In the command line prompt, change the working directory to the project’s directory, and type ant command. You should see the following output:

run-ant-build

Typing ant command without any arguments will execute the default target. In our build file, the default target is dist which depends on compile target which depends on init target. Hence these 3 targets are executed in the following order: init, compile and dist. The clean target was not executed because it is standalone.

Check the project’s directory and you see the build directory was created and the compiled .class files are put in, as a result of the compile target.

And the dist target created the dist directory and generate an executable JAR file in this directory. Now from the command line you can type the following command to run the program from JAR file:

java -jar dist\ContactManager-20191101.jar
And you will see this output:

error-run-first-time

It throws SQLException because no JDBC driver for MySQL found in the classpath.

Click here to download JDBC driver for MySQL. Download and extract the ZIP archive, e.g. mysql-connector-java-8.0.18.zip and you will see the JAR file named mysql-connector-java-8.0.18.jar.

Next, create a directory named lib under the project’s directory and copy the MySQL JDBC driver JAR file to it.

In the build.xml file, add two new properties:

<property name="lib" location="lib"/>
<property name="JdbcDriver" value="mysql-connector-java-8.0.18.jar"/>
In the <manifest> section, add a new attribute:

<attribute name="Class-Path" value="${JdbcDriver}"/>
This specifies the MySQL JDBC driver JAR file referenced by the executable JAR file. And add the <copy> task right after the <jar> task:

<copy file="${lib}\${JdbcDriver}" todir="${dist}" overwrite="true" />
This tells Ant to copy the MySQL JDBC driver JAR file to the distribution directory when the dist target is executed.

The complete build.xml file now looks like this:

<project name="ContactProject" default="dist" basedir=".">

  <property name="src" location="src"/>
  <property name="build" location="build"/>
  <property name="dist" location="dist"/>
  <property name="lib" location="lib"/>
  <property name="JdbcDriver" value="mysql-connector-java-8.0.18.jar"/>

  <target name="init">
    <tstamp/>
    <mkdir dir="${build}"/>
  </target>

  <target name="compile" depends="init" description="compile the source">
    <javac srcdir="${src}" destdir="${build}"/>
  </target>

  <target name="dist" depends="compile" description="generate the distribution">
    <mkdir dir="${dist}"/>

    <jar jarfile="${dist}/ContactManager-${DSTAMP}.jar" basedir="${build}">
            <manifest>
                <attribute name="Main-Class" value="com.mycompany.ContactInserter"/>
                <attribute name="Class-Path" value="${JdbcDriver}"/>
            </manifest>            
    </jar>
    
    <copy file="${lib}\${JdbcDriver}" todir="${dist}" overwrite="true" />
    
  </target>

  <target name="clean" description="clean up">
    <delete dir="${build}"/>
    <delete dir="${dist}"/>
  </target>
</project>
Now, type ant clean to delete everything the build and dist directories. You will see the following output:

run-clean-target

Type ant again to rebuild the project. You will see the MySQL JDBC driver JAR file is copied to the dist directory, along with the generated executable JAR file of the program.

Now you can type the following command to run the program from the JAR file:

java -jar dist\ContactManager-20191101.jar
You will see the following output:

run-jar-file

The program runs successfully and prints the message “A row was inserted”. You can check the database to confirm.

So each time you make changes to the code, you can run ant command to rebuild the project, conveniently.

That’s how to get started with Apache Ant – a popular build tool for Java projects. This lesson just scratches the surface, and Ant has more useful features which you can explore on Ant official homepage.


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Add comment

   


Comments 

#4Chester Parkes2023-11-27 18:52
Very helpful and well put together. Thank you!
Quote
#3VikashSolanki2022-12-05 23:49
it was very helpful for me but i need to how to use dependency instead of manually jar file in ANT project in java programming language.
Quote
#2Wilson Apagu2020-05-16 09:16
So interesting tutorial, needs more from you sir
Quote
#1Jeenath kamila2020-05-13 04:10
would like to know full versions and coding details about Java since Java 1.0 to Java 14
Thankyou
Quote