build.xml Required by Apache Ant

Q

What is the build.xml Required by Apache Ant?

✍: FYIcenter.com

A

The build.xml file required by Apache Ant is XML file that contains instructions to build final targets using system commands and source files.

Here is a tutorial on how to create a build.xml file and use "ant" to build a simple Java project.

1. Create a build.xml as shown below:

> type build.xml 

<?xml version="1.0" encoding="UTF-8"?>
 <!-- Set the project name, basedir and default target to be executed-->
<project name="Ant-Build-Project-Test" default="mainTarget" basedir=".">

  <!-- Sets the properties here-->
  <property name="src.dir" location="src" />
  <property name="build.dir" location="bin" />
 
  <!-- Target for deleting the existing directories-->
  <target name="clean">
    <delete dir="${build.dir}" />
  </target>
 
  <!-- Target for creating the new directories-->
  <target name="makedir">
    <mkdir dir="${build.dir}" />
  </target>
 
  <!-- Target for compiling the java code-->
  <target name="compile" depends="clean, makedir">
    <javac srcdir="${src.dir}" destdir="${build.dir}">
    </javac>  
  </target>
 
  <!-- Defualt target to run all targets-->
  <target name="mainTarget" depends="compile">
    <description>Main target</description>
  </target>

</project>

2. Verify your Apache Ant installation:

> \local\ant\bin\ant.bat -version 

Apache Ant(TM) version 1.10.10 compiled on April 12 2021

3. Run the default target defined in the build.xml. The build process will fail, because there is no "src" sub-directory and Java source code to compile.

> \local\ant\bin\ant.bat 

Buildfile: \Users\fyicenter\build.xml

clean:

makedir:
    [mkdir] Created dir: \Users\fyicenter\bin

compile:
    [javac] build.xml:21: warning: 'includeantruntime' was not set, 
  defaulting to build.sysclasspath=last; set to false for repeatable builds

BUILD FAILED
  build.xml:21: srcdir "\Users\fyicenter\src" does not exist!

Total time: 0 seconds

4. Run the default target again with a sample Java source code.

> mkdire src 
> edit src\Hello.java 

public class Hello {
   public static void main(String[] args) {
      System.out.println("Hello world!");
   }
}

> \local\ant\bin\ant.bat 
Buildfile: build.xml

clean:
   [delete] Deleting directory bin

makedir:
    [mkdir] Created dir: bin

compile:
    [javac] Compiling 1 source file to bin

mainTarget:

BUILD SUCCESSFUL
Total time: 0 seconds

5. Verify the build result:

> dir bin 
336   Hello.class

> java -cp bin Hello 
Hello world!

 

⇒ Download Apache Ant Source Package

⇐ Run Apache Ant on Windows, Mac and Linux

⇑ Apache Ant - Java Build Tool

⇑⇑ Java/JAR Tools

2021-07-10, 245👍, 0💬