Ant Tasks – Quick Guide


Table of Contents

Apache Ant Tasks – Quick Guide



”;


Apache Ant Tasks – Introduction

ANT stands for Another Neat Tool. It is a Java-based build tool from computer software development company Apache. Before going into the details of Apache Ant, let us first understand why we need a build tool.

Need for a Build Tool

On an average, a developer spends a substantial amount of time doing mundane tasks like build and deployment that include −

  • Compiling the code

  • Packaging the binaries

  • Deploying the binaries to the test server

  • Testing the changes

  • Copying the code from one location to another

To automate and simplify the above tasks, Apache Ant is useful. It is an Operating System build and deployment tool that can be executed from the command line. Ant tasks simplifies executions of operations.

History of Apache Ant

Ant was created by software developer James Duncan Davidson who is also the original creator of webserver application Tomcat.

Ant was originally used to build Tomcat, and was bundled as a part of Tomcat distribution.

It was born out of the problems and complexities associated with the Apache Make tool.

It was promoted as an independent project in Apache in the year 2000. The latest version of Apache Ant as on October 2021 is 1.10.12.

Features of Apache Ant

The features of Apache Ant are listed below −

  • It is the most complete Java build and deployment tool available.

  • It is platform neutral and can handle platform specific properties, such as file separators.

  • It can be used to perform platform specific tasks such as modifying the modified time of a file using ”touch” command.

  • Ant scripts are written using plain XML. If you are already familiar with XML, you can learn Ant pretty quickly.

  • Ant is good at automating complicated repetitive tasks.

  • Ant comes with a big list of predefined tasks.

  • Ant provides an interface to develop custom tasks.

  • Ant can be easily invoked from the command line and it can integrate with free and commercial IDEs.

Apache Ant Tasks – Environment Setup

Apache Ant is distributed under the Apache Software License which is a fully-fledged open source license certified by the open source initiative.

The latest Apache Ant version, including its full-source code, class files, and documentation can be found at https://ant.apache.org.

Installing Apache Ant

It is assumed that you have already downloaded and installed Java Development Kit (JDK) on your computer. If not, please follow the instructions available at file:///C:/java/java_environment_setup.htm

  • Ensure that the JAVA_HOME environment variable is set to the folder, where your JDK is installed.

  • Download the binaries from https://ant.apache.org

  • Unzip the zip file to a convenient location c:folder by using Winzip, winRAR, 7-zip or similar tools.

  • Create a new environment variable called ANT_HOME that points to the Ant installation folder. In this case, it is c:apache-ant-1.10.12-bin folder.

  • Append the path to the Apache Ant batch file to the PATH environment variable. In our case, this would be the c:apache-ant-1.10.12-binbin folder.

Verifying the Installation

To verify the successful installation of Apache Ant on your computer, type ant on your command prompt.

You should see an output as given below −


C:>ant -version
Apache Ant(TM) version 1.10.12 compiled on October 13 2021

If you do not see the above output, then please verify that you have followed the installation steps properly.

Installing Eclipse

This tutorial also covers integration of Ant with Eclipse integrated development environment (IDE). Hence, if you have not installed Eclipse, please download and install Eclipse.

Steps to install Eclipse

  • Download the latest Eclipse binaries from www.eclipse.org

  • Unzip the Eclipse binaries to a convenient location, say c:folder.

  • Run Eclipse from c:eclipseeclipse.exe.

Apache Ant Tasks – BaseName

Description

Basename task determines the base name of the specified file/directory while removing the suffix if passed. In case of full path of file, the name of the file is used. In case of directory path, the name of the last directory is used.

Properties






Sr.No Attributes & Description
1

File

The path to take the basename of. (Mandatory)

2

Property

The name of the property to set. (Mandatory)

3

Suffix

The suffix to remove from the resulting basename (specified either with or without the .). (Optional)

Example

Usage

Create build.xml with the following content −


<?xml version="1.0"?>
<project name="TutorialPoint" default="info">
   <target name="info">
      <basename property="cmdname" file="D:/usr/local/application.exe"
         suffix=".exe"/>
      <echo message="${cmdname}"></echo>
   </target>
</project>

Output

Running Ant on the above build file produces the following output −


F:tutorialspointant>ant
Buildfile: F:tutorialspointantbuild.xml

info:
   [echo] application

BUILD SUCCESSFUL
Total time: 0 seconds

Apache Ant Tasks – GZip

Description

Gzip task creates archive based on GZip, BZip2 or XZ algorithm. Output file is generated only if it is not present or source is newer.

Properties





Sr.No Attributes & Description
1

src

The file/collection to gzip/bzip/xz. (Mandatory)

2

Destfile

the destination file to create. (Mandatory)

Example

Usage

Create build.xml with the following content:


<?xml version="1.0"?>
<project name="TutorialPoint" default="info">
   <target name="info">
      <gzip src="test.txt" destfile="text.gz" />
      <echo>File archived.</echo>
   </target>
</project>

Output

Create a text.txt file with some content in the same folder. Now running Ant on the above build file produces the following output −


F:tutorialspointant>ant
Buildfile: F:tutorialspointantbuild.xml

info:
     [gzip] Building: F:tutorialspointanttext.gz
     [echo] File archived.

BUILD SUCCESSFUL
Total time: 0 seconds

You can verify that the text.gz file created.

Apache Ant Tasks – GUnzip

Description

Gunzip task extracts an archive using GZip, BZip2 or XZ algorithm. Output file is generated only if it is not present or source resource is newer. If dest is omitted, the parent dir of src is used.

Properties





Sr.No Attributes & Description
1

src

The file/collection to expand. (Mandatory)

2

Dest

The destination file or directory. (Optional)

Example

Usage

Create build.xml with the following content:


<?xml version="1.0"?>
   <project name="TutorialPoint" default="info">
   <target name="info">
      <gunzip src="text.gz" dest="text.txt"/>
      <echo>File extracted.</echo>
   </target>
</project>

Output

Let”s extract the a text.gz file to text.txt. Now running Ant on the above build file produces the following output −


F:tutorialspointant>ant
Buildfile: F:tutorialspointantbuild.xml

info:
   [gunzip] Expanding text.gz to F:tutorialspointanttext.txt
   [echo] File extracted.

BUILD SUCCESSFUL
Total time: 0 seconds

You can verify that the text.txt file is created.

Apache Ant Tasks – Chmod

Description

Chmod task works on Unix and works similar to chmod command. It changes the permissions of a file or all files inside specified directories.

Properties















Sr.No Attributes & Description
1

File

The file or single directory of which the permissions must be changed. (Mandatory)

2

Dir

The directory which holds the files whose permissions must be changed. (Mandatory)

3

Perm

The new permissions. (Mandatory)

4

Includes

comma- or space-separated list of patterns of files that must be included. (Optional)

5

Excludes

comma- or space-separated list of patterns of files that must be excluded. (Optional)

6

Defaultexcludes

indicates whether default excludes should be used or not (yes|no). (Optional). Default is yes.

7

Parallel

process all specified files using a single chmod command. (Optional). Default is true.

8

Type

One of file, dir or both. If set to file, only the permissions of plain files are going to be changed. If set to dir, only the directories are considered. (Optional). Default is file.

9

Maxparallel

Limit the amount of parallelism by passing at most this many sourcefiles at once. Set it to negative integer for unlimited. (Optional). Default is infinite.

10

Verbose

Whether to print a summary after execution or not. (Optional). Default is false.

11

OS

list of Operating Systems on which the command may be executed. (Optional)

12

Osfamily

OS family as used. (Optional).Default is Unix.

Example

Usage

Create build.xml with the following content −


<?xml version="1.0"?>
<project name="TutorialPoint" default="info">
   <target name="info">
      <chmod file="start.sh" perm="ugo+rx"/>
   </target>
</project>

Above script makes start.sh as readable and executable on a Unix machine.

Apache Ant Tasks – Concat

Description

Concat task concatenate one or more resources to a single file or to console. The destination file is created if it does not exist unless the resource list is empty and ignoreempty flag is true.

Properties















Sr.No Attributes & Description
1

Destfile

The destination file for the concatenated stream. If not specified the console will be used instead.

2

Append

Specifies whether or not the file specified by destfile should be appended.

3

Overwrite

Specifies whether or not the file specified by destfile should be written to even if it is newer than all source files.

4

ForceReadonly

Overwrite read-only destination files.

5

Encoding

Specifies the encoding for the input files.

6

Outputencoding

The encoding to use when writing the output file.

7

Fixlastline

Specifies whether or not to check if each file concatenated is terminated by a new line. If this attribute is yes a new line will be appended to the stream if the file did not end in a new line.

8

EOL

Specifies what the end of line character are for use by the fixlastline attribute.

9

Binary

If this attribute is set to true, the task concatenates the files in a byte by byte fashion. If this attribute is false, concat will not normally work for binary files due to character encoding issues. If this option is set to true, the destfile attribute must be set, and the task cannot used nested text. Also the attributes encoding, outputencoding, filelastline cannot be used.

10

Filterbeforeconcat

If this attribute is set to true, the task applies the filterchain to each input after applying fixlastline. If this attribute is false, concat will apply the filterchain only once to the already concatenated inputs. Filtering of header and footer is not affected by this setting.

11

Ignoreempty

Specifies whether or not the file specified by destfile should be created if the source resource list is empty.

12

Resourcename

Specifies the name reported if this task is exposed as a resource.

Example

Usage

Create build.xml with the following content −


<?xml version="1.0"?>
<project name="TutorialPoint" default="info">
   <target name="info">
      <concat>
         <fileset dir="messages" includes="*test*"/>
      </concat>
   </target>
</project>

Above script will read messages folder and concatenates contents of file having test in their name and show them on console.

Output

Let”s create a test.txt with content as “Welcome to tutorialspoint.com” in messages folder. Now running Ant on the above build file produces the following output −


F:tutorialspointant>ant
Buildfile: F:tutorialspointantbuild.xml

info:
   [concat] Welcome to tutorialspoint.com

BUILD SUCCESSFUL
Total time: 0 seconds

Apache Ant Tasks – Condition

Description

Condition task sets the property value to true by default if condition is true; otherwise, the property is not set. You can set the value to something other than the default by specifying the value attribute.

Properties






Sr.No Attributes & Description
1

Property

The name of the property to set. (Mandatory)

2

Value

The value to set the property to.

3

Else

The value to set the property to if the condition evaluates to false.

Example

Usage

Create build.xml with the following content −


<?xml version="1.0"?>
<project name="TutorialPoint" default="info">
   <condition property="isWindows">
      <os family="windows"/>
   </condition>
   <target name="info">
      <echo message="${isWindows}"></echo>
   </target>
</project>

Above script will set a variable is Windows based on the underlying operation system is windows or not.

Output

Running Ant on the above build file produces the following output −


F:tutorialspointant>ant
Buildfile: F:tutorialspointantbuild.xml

info:
   [echo] true

BUILD SUCCESSFUL
Total time: 0 seconds

Apache Ant Tasks – Copy

Description

Copy task copies a file/resource collection to a new file or directory. Files are only copied if the source file is newer than the destination file, or when the destination file does not exist.

Properties



















Sr.No Attributes & Description
1

File

The file to copy. (Mandatory)

2

Preservelastmodified

Give the copied files the same last modified time as the original source files.

3

Tofile

The file to copy to.

4

Todir

The directory to copy to.

5

Overwrite

Overwrite existing files even if the destination files are newer.

6

Force

Overwrite read-only destination files.

7

Filtering

Indicates whether token filtering using the global build-file filters should take place during the copy.

8

Flatten

Ignore the directory structure of the source files, and copy all files into the directory specified by the todir attribute.

9

includeEmptyDirs

Copy any empty directories included in the FileSet(s).

10

Failonerror

If false, log a warning message, but do not stop the build, when the file to copy does not exist or one of the nested filesets points to a directory that doesn”t exist or an error occurs while copying.

11

Quiet

If true and failonerror is false, then do not log a warning message when the file to copy does not exist or one of the nested filesets points to a directory that doesn”t exist or an error occurs while copying.

12

Verbose

Log the files that are being copied.

13

Encoding

The encoding to assume when filter-copying the files.

14

Outputencoding

The encoding to use when writing the files.

15

Enablemultiplemappings

If true the task will process to all the mappings for a given source path. If false the task will only process the first file or directory. This attribute is only relevant if there is a mapper subelement.

16

Granularity

The number of milliseconds leeway to give before deciding a file is out of date. This is needed because not every file system supports tracking the last modified time to the millisecond level. This can also be useful if source and target files live on separate machines with clocks being out of sync.

Example

Usage

Create build.xml with the following content −


<?xml version="1.0"?>
<project name="TutorialPoint" default="info">
   <target name="info">
      <copy file="text.txt" tofile="textcopy.txt"></copy>
   </target>
</project>

Above script will copy a file say text.txt in the current directory as textcopy.txt.

Output

Running Ant on the above build file produces the following output −


F:tutorialspointant>ant
Buildfile: F:tutorialspointantbuild.xml

info:
   [echo] Copying 1 file to F:tutorialspointant

BUILD SUCCESSFUL
Total time: 1 second

Apache Ant Tasks – Delete

Description

Delete task deletes a single file, a specified directory and all its files and subdirectories, or a set of files specified by one or more resource collections.

Properties












Sr.No Attributes & Description
1

File

The file to delete, specified as either the simple filename (if the file exists in the current base directory), a relative-path filename, or a full-path filename.

2

DIR

The directory to delete, including all its files and subdirectories.

3

Verbose

Whether to show the name of each deleted file.

4

Quiet

If the specified file or directory does not exist, do not display a diagnostic message.

5

Failonerror

Controls whether an error (such as a failure to delete a file) stops the build or is merely reported to the screen. Only relevant if quiet is false.

6

Includeemptydirs

Whether to delete empty directories when using filesets.

7

Deleteonexit

Indicates whether to use File#deleteOnExit() if there is a failure to delete a file. This causes the JVM to attempt to delete the file when the JVM process is terminating.

8

removeNotFollowedSymlinks

Whether symbolic links (not the files/directories they link to) should be removed if they haven”t been followed because followSymlinks was false or the maximum number of symbolic links was too big.

9

performGCOnFailedDelete

If Ant fails to delete a file or directory it will retry the operation once. If this flag is set to true it will perform a garbage collection before retrying the delete.

Example

Usage

Create build.xml with the following content −


<?xml version="1.0"?>
<project name="TutorialPoint" default="info">
   <target name="info">
      <delete file="text.txt" verbose="true"></delete>
   </target>
</project>

Output

Running Ant on the above build file produces the following output −


F:tutorialspointant>ant
Buildfile: F:tutorialspointantbuild.xml

info:
   [delete] Deleting: F:tutorialspointanttext.txt

BUILD SUCCESSFUL
Total time: 0 seconds

Apache Ant Tasks – EAR

Description

Ear task is an extension of the Jar task with special treatment for files that should end up in an Enterprise Application archive.

Properties

































Sr.No Attributes & Description
1

Destfile

the EAR file to create.

2

app.xml

The deployment descriptor to use (META-INF/application.xml).

3

Basedir

the directory from which to jar the files.

4

Compress

Not only store data but also compress them. Unless you set the keep compression attribute to false, this will apply to the entire archive, not only the files you”ve added while updating.

5

Keepcompression

For entries coming from existing archives (like nested zipfilesets or while updating the archive), keep the compression as it has been originally instead of using the compress attribute.

6

Encoding

The character encoding to use for filenames inside the archive.

7

Filesonly

Store only file entries.

8

Include

comma- or space-separated list of patterns of files that must be included.

9

Includesfile

name of a file. Each line of this file is taken to be an include pattern.

10

Excludes

comma- or space-separated list of patterns of files that must be excluded.

11

Excludesfile

Name of a file. Each line of this file is taken to be an exclude pattern.

12

Defaultexcludes

Indicates whether default excludes should be used or not (yes|no).

13

Menifest

The manifest file to use.

14

Filesetmanifest

Behavior when a manifest file is found in a zipfileset or zipgroupfileset file. Valid values are skip, merge, and mergewithoutmain. merge will merge all of the manifests together, and merge this into any other specified manifests. mergewithoutmain merges everything but the Main section of the manifests.

15

Whenmanifestonly

Behavior when no files match. Valid values are fail, skip, and create.

16

Manifestencoding

The encoding used to read the JAR manifest, when a manifest file is specified.

17

Index

whether to create an index list to speed up classloading. Unless you specify additional jars with nested indexjars elements, only the contents of this jar will be included in the index.

18

IndexMetaInf

Whether to include META-INF and its children in the index. Doesn”t have any effect if index is false. Oracle”s jar implementation used to skip the META-INF directory and Ant followed that example. The behavior has been changed with Java 5. In order to avoid problems with Ant generated jars on Java 1.4 or earlier, Ant will not include META-INF unless explicitly asked to.

19

Manifestencoding

The encoding used to read the JAR manifest, when a manifest file is specified.

20

Update

indicates whether to update or overwrite the destination file if it already exists.

21

Duplicate

Behavior when a duplicate file is found. Valid values are add, preserve, and fail.

22

Roundup

Whether the file modification times will be rounded up to the next even number of seconds.

23

Level

Non-default level at which file compression should be performed. Valid values range from 0 (no compression/fastest) to 9 (maximum compression/slowest).

24

Preserve0permissions

When updating an archive or adding entries from a different archive Ant will assume that a Unix permissions value of 0 (nobody is allowed to do anything to the file/directory) means that the permissions haven”t been stored at all rather than real permissions and will instead apply its own default values.

25

UseLanguageEncodingFlag

Whether to set the language encoding flag if the encoding is UTF-8. This setting doesn”t have any effect if the encoding is not UTF-8.

26

CreateUnicodeExtraFields

Whether to create Unicode extra fields to store the file names a second time inside the entry”s metadata.

27

FallbacktoUTF8

Whether to use UTF-8 and the language encoding flag instead of the specified encoding if a file name cannot be encoded using the specified encoding.

28

MergeClassPathAttributes

Whether to merge the Class-Path attributes found in different manifests (if merging manifests). If false, only the attribute of the last merged manifest will be preserved.

29

FlattenAttributes

Whether to merge attributes occurring more than once in a section (this can only happen for the Class-Path attribute) into a single attribute.

30

Zip64Mode

When to use Zip64 extensions for entries. The possible values are never, always and as-needed.

Example

Usage

Create build.xml with the following content −


<?xml version="1.0"?>
<project name="TutorialPoint" default="info">
   <property name="src.dir" value="src" />
   <property name="build.dir" value="build" />
   <target name="info">
      <ear destfile="${build.dir}/myapp.ear" appxml="${src.dir}/metadata/application.xml">
         <fileset dir="${build.dir}" includes="*.jar,*.war"/>
      </ear>
   </target>
</project>

Above script will create an ear file in the current directory as myapp.ear.

Output

Running Ant on the above build file produces the following output −


F:tutorialspointant>ant
Buildfile: F:tutorialspointantbuild.xml

info:
   [ear] Building ear: F:tutorialspointantbuildmyapp.ear

BUILD SUCCESSFUL
Total time: 1 second

Apache Ant Tasks – Fail

Description

Fail task is used to exit the current build by throwing a BuildException, optionally printing additional information. The message of the Exception can be set via the message attribute or character data nested into the element.

Properties







Sr.No Attributes & Description
1

Message

A message giving further information on why the build exited.

2

If

Only fail if a property of the given name exists in the current project

3

Unless

Only fail if a property of the given name doesn”t exist in the current project

4

Status

Exit using the specified status code; assuming the generated Exception is not caught, the JVM will exit with this status.

Example

Usage

Create build.xml with the following content −


<?xml version="1.0"?>
<project name="TutorialPoint" default="info">
   <property name="build.dir" value="build" />
   <target name="info">
      <fail unless="src.dir"/>
   </target>
</project>

Above script will fail the build as src.dir is not set.

Output

Running Ant on the above build file produces the following output −


F:tutorialspointant>ant
Buildfile: F:tutorialspointantbuild.xml

info:

BUILD FAILED
F:tutorialspointantbuild.xml:5: unless=src.dir

Total time: 0 seconds

Apache Ant Tasks – Import

Description

Import task imports another build file into the project.

Properties







Sr.No Attributes & Description
1

File

The file to import. If this is a relative file name, the file name will be resolved relative to the importing file. Note: this is unlike most other Ant file attributes, where relative files are resolved relative to basedir.

2

Optional

If true, do not stop the build if the file does not exist.

3

As

Specifies the prefix prepended to the target names.

4

prefixSeparator

Specifies the separator to be used between the prefix and the target name.

Example

Usage

Create build.xml with the following content −


<?xml version="1.0"?>
<project name="TutorialPoint" default="info">
   <import file="nested.xml" as="nested"/>
   <target name="info" depends="nested.echo">      
   </target>
</project>

And a nested.xml with the following content −


<project>
   <target name="setUp">
      <property name="build.dir" value="build"/>
   </target>
   <target name="echo" depends="setUp">
      <echo>build.dir is set as build</echo>
   </target>
</project>

Above script will create an ear file in the current directory as myapp.ear.

Output

Running Ant on the above build file produces the following output −


F:tutorialspointant>ant
Buildfile: F:tutorialspointantbuild.xml

setUp:

nested.echo:
   [echo] build.dir is set as build

info:

BUILD SUCCESSFUL
Total time: 0 seconds

Apache Ant Tasks – Java

Description

Java task executes a Java class within the running JVM or forks another JVM if specified using fork=true;

Properties
































Sr.No Attributes & Description
1

Classname

The Java class to execute.

2

Jar

The location of the jar file to execute. fork must be set to true if this option is selected.

3

Module

The initial or main module to resolve (must have a Main-Class entry in the manifest). fork must be set to true if this option is selected.

4

Sourcefile

The location of a “.java” file or a file containing shebang with Java source code. Set this attribute to run Java single file source programs, a feature introduced in Java 11. fork must be set to true if this option is selected.

5

Classpath

The classpath to use.

6

Classpathref

The classpath to use, given as reference to a Path defined elsewhere.

7

Modulepath

Specify where to find application modules. A list of directories of modules, module files or exploded modules.

8

modulepathref

The modulepath to use, given as reference to a Path defined elsewhere.

9

Fork

If enabled triggers the class execution in another JVM.

10

Spawn

If enabled allows to start a process which will outlive Ant. Requires that fork is true, and not compatible with timeout, input, output, error, result attributes

11

Sourcefile

The location of a “.java” file or a file containing shebang with Java source code. Set this attribute to run Java single file source programs, a feature introduced in Java 11. fork must be set to true if this option is selected.

12

jvm

The command used to invoke JVM. The command is resolved by java.lang.Runtime.exec(). Ignored if fork is false.

13

Maxmemory

Max amount of memory to allocate to the forked JVM, ignored if fork is false.

14

Failonerror

Stop the build process if the command exits with a return code other than 0.

15

resultproperty

The name of a property in which the return code of the command should be stored. Only of interest if failonerror is false and if fork is true.

16

DIR

The directory to invoke the JVM in, ignored if fork is false.

17

Output

Name of a file to which to write the output. If the error stream is not also redirected to a file or property, it will appear in this output.

18

Error

The file to which the standard error of the command should be redirected.

19

logerror

This attribute is used when you wish to see error output in Ant”s log and you are redirecting output to a file/property. The error output will not be included in the output file/property. If you redirect error with the error or errorProperty attributes, this will have no effect.

20

Append

Whether output and error files should be appended to or overwritten.

21

Outputproperty

The name of a property in which the output of the command should be stored. Unless the error stream is redirected to a separate file or stream, this property will include the error output.

22

Errorproperty

The name of a property in which the standard error of the command should be stored.

23

Input

A file from which the executed command”s standard input is taken. This attribute is mutually exclusive with the input string attribute.

24

Inputstring

A string which serves as the input stream for the executed command. This attribute is mutually exclusive with the input attribute.

25

Newenvironment

Do not propagate old environment when new environment variables are specified.

26

Timeout

Stop the command if it doesn”t finish within the specified time (given in milliseconds). It is highly recommended to use this feature only if fork is true.

27

Clonevm

If set to true, then all system properties and the bootclasspath of the forked JVM will be the same as those of the JVM running Ant.

28

Discardoutput

Whether output should completely be discarded. This setting is incompatible with any setting that redirects output to files or properties. If you set this to true error output will be discared as well unless you redirect error output to files, properties or enable logError.

29

Discarderror

Whether error output should completely be discarded. This setting is incompatible with any setting that redirects error output to files or properties as well as logError.

Example

Usage

Create TestMessage.java with the following content −


public class TestMessage {
   public static void main(String[] args) {
      System.out.println("Welcome to tutorialspoint.com");
   }
}

Create build.xml with the following content −


<?xml version="1.0"?>
<project name="TutorialPoint" default="info">
   <target name="info">      
      <java classname="TestMessage" classpath="."/>
   </target>
</project>

Above script will run a java class file to print output.

Output

Running Ant on the above build file produces the following output −


F:tutorialspointant>ant
Buildfile: F:tutorialspointantbuild.xml

info:
   [java] Welcome to tutorialspoint.com

BUILD SUCCESSFUL
Total time: 0 seconds

Apache Ant Tasks – Javac

Description

Javac task compiles a Java source tree. The source and destination directory will be recursively scanned for Java source files to compile. Only .java files that have no corresponding .class file or where the .class file is older than the .java file will be compiled.

Properties

















































Sr.No Attributes & Description
1

Srcdir

Location of the java files.

2

Destdir

Location to store the class files.

3

Includes

Comma- or space-separated list of patterns of files that must be included.

4

Includesfile

Name of a file. Each line of this file is taken to be an include pattern.

5

Excludes

Comma- or space-separated list of patterns of files that must be excluded.

6

Excludesfile

Name of a file. Each line of this file is taken to be an exclude pattern.

7

Defaultexcludes

Indicates whether default excludes should be used or not (yes|no).

8

Classpath

The classpath to use.

9

Sourcepath

The sourcepath to use. To suppress the sourcepath switch, use sourcepath=””.

10

Bootclasspath

Location of bootstrap class files.

11

Classpathref

The classpath to use, given as a reference to a path defined elsewhere.

12

Sourcepathref

The sourcepath to use, given as a reference to a path defined elsewhere.

13

Bootclasspathref

The bootstrapclasspath to use, given as a reference to a path defined elsewhere.

14

Extdirs

Location of installed extensions.

15

Encoding

Encoding of source files.

16

NSowarn

Indicates whether the -nowarn switch should be passed to the compiler.

17

Debug

Indicates whether source should be compiled with debug information. If set to off, -g:none will be passed on the command line for compilers that support it (for other compilers, no command line argument will be used). If set to true, the value of the debuglevel attribute determines the command line argument.

18

Debuglevel

Keyword list to be appended to the -g command-line switch. Legal values are none or a comma-separated list of the following keywords: lines, vars, and source.

19

Optimize

Indicates whether source should be compiled with optimization. Note that this flag is just ignored by Sun”s javac since JDK 1.3 (because compile-time optimization is unnecessary).

20

Deprecation

Indicates whether source should be compiled with deprecation information.

21

Verbose

Asks the compiler for verbose output.

22

Depend

Enables dependency tracking for compilers that support this (jikes and classic).

23

includeAntRuntime

Whether to include the Ant run-time libraries in the classpath. It is usually best to set this to false so the script”s behavior is not sensitive to the environment in which it is run.

24

includeJavaRuntime

Whether to include the default run-time libraries from the executing JVM in the classpath.

25

Fork

Whether to execute javac using the JDK compiler externally.

26

Executable

Complete path to the javac executable to use in case of fork is yes.

27

memoryInitialSize

The initial size of the memory for the underlying JVM, if javac is run externally. (Examples: 83886080, 81920k, or 80m)

28

memoryMaximumSize

The maximum size of the memory for the underlying JVM, if javac is run externally; ignored otherwise. (Examples: 83886080, 81920k, or 80m)

29

Failonerror

Indicates whether compilation errors will fail the build.

30

Errorproperty

The property to set to true if compilation fails.

31

Source

Java language features accepted by compiler, as specified by the -source command-line switch. Valid feature versions are 1.3, 1.4, 1.5 or 5, etc.

32

Target

Generate class files for specific JVM version (cross-compile).

33

Compiler

The compiler implementation to use.

34

listfiles

Indicates whether the source files to be compiled will be listed.

35

TempDir

Where Ant should place temporary files. This is only used if the task is forked and the command line args length exceeds 4 kB.

36

updatedProperty

The property to set to true if compilation has taken place and has been successful.

37

includeDestClasses

This attribute controls whether to include the destination classes directory in the classpath given to the compiler. If set to true (default), previously compiled classes are on the classpath for the compiler.

38

createMissingPackageInfoClass

Some package level annotations in package-info.java files don”t create any package-info.class files so Ant would recompile the same file every time.

39

MSodulepath

Specify where to find application modules. A list of directories of modules, module files or exploded modules.

40

Modulepathref

The modulepath to use, given as reference to a path defined elsewhere.

41

Modulesourcepath

Specify where to find input source files for multiple module compilation.

42

Modulesourcepathref

The modulesourcepath to use, given as reference to a path defined elsewhere.

43

Upgrademodulepath

Specify the location of modules that replace upgradeable modules in the runtime image.

44

Upgrademodulepathref

The upgrademodulepath to use, given as reference to a path defined elsewhere.

45

NSativeheaderdir

Specify where to place generated native header files.

46

Release

Specify the value for the –release switch. When set and running on JDK 9+ the source and target attributes as well as the bootclasspath will be ignored.

Example

Usage

Create TestMessage.java with the following content in src directory:


public class TestMessage {
   public static void main(String[] args) {
      System.out.println("Welcome to tutorialspoint.com");
   }
}

Create build.xml with the following content:


<?xml version="1.0"?>
<project name="TutorialPoint" default="info">
   <target name="info">      
      <javac srcdir="src" destdir="build"/>
   </target>
</project>

Above script will run a java class file to print output.

Output

Running Ant on the above build file produces the following output −


F:tutorialspointant>ant
Buildfile: F:tutorialspointantbuild.xml

info:
   [javac] F:tutorialspointantbuild.xml:4: warning: ''includeantruntime'' was not set, defaulting to build.sysclasspath=last; set to false for repeatable builds
   [javac] Compiling 1 source file to F:tutorialspointantbuild

BUILD SUCCESSFUL
Total time: 0 seconds

Apache Ant Tasks – Length

Description

Length task display or set a property containing length information for a string, a file, or one or more nested resource collections. It can also be used as a condition.

Properties











Sr.No Attributes & Description
1

Property

The property to set.

2

Mode

File length mode; when all the resulting value is the sum of all included resources” lengths; when each the task outputs the absolute path and length of each included resource, one per line.

3

File

Single file whose length to report.

4

Resource

Single resource whose length to report (using extended properties handling).

5

String

The string whose length to report.

6

Trim

Whether to trim when operating on a string.

7

Length

Comparison length.

8

When

Comparison type: equal, eq, greater, gt, less, lt, ge (greater or equal), ne (not equal), le (less or equal).

Example

Usage

Create build.xml with the following content −


<?xml version="1.0"?>
<project name="TutorialPoint" default="info">
   <length string="tutorialspoint" property="text.size"/>
   <target name="info">            
      <echo message="${text.size}"/>
   </target>
</project>

Output

Running Ant on the above build file produces the following output −


F:tutorialspointant>ant
Buildfile: F:tutorialspointantbuild.xml

info:
   [echo] 14

BUILD SUCCESSFUL
Total time: 0 seconds

Apache Ant Tasks – LoadFile

Description

Loadfile task loads a file and sets its content into property.

Properties








Sr.No Attributes & Description
1

srcFile

Source File.

2

Property

Property to save to.

3

Encoding

Encoding to use when loading the file.

4

failonerror

Whether to halt the build on failure.

5

Quiet

Do not display a diagnostic message (unless Apache Ant has been invoked with the -verbose or -debug switches) or modify the exit status to reflect an error. Setting this to true implies setting failonerror to false.

Usage

Create message.txt with the following content −


Welcome to tutorialspoint.com

Example

Create build.xml with the following content −


<?xml version="1.0"?>
<project name="TutorialPoint" default="info">
   <loadfile property="message" srcFile="message.txt"/>
   <target name="info">            
      <echo message="${message}"/>
   </target>
</project>

Output

Running Ant on the above build file produces the following output −


F:tutorialspointant>ant
Buildfile: F:tutorialspointantbuild.xml

info:
   [echo] Welcome to tutorialspoint.com

BUILD SUCCESSFUL
Total time: 0 seconds

Apache Ant Tasks – MkDir

Description

Mkdir task creates a directory. Also non-existent parent directories are created, when necessary. Does nothing if the directory already exists.

Properties




Sr.No Attributes & Description
1

DIR

The directory to create.

Example

Usage

Create build.xml with the following content −


<?xml version="1.0"?>
<project name="TutorialPoint" default="info">
   <mkdir dir="dist"/>
   <target name="info">
   </target>
</project>

Output

Running Ant on the above build file produces the following output −


F:tutorialspointant>ant
Buildfile: F:tutorialspointantbuild.xml
   [mkdir] Created dir: F:tutorialspointantdist

info:

BUILD SUCCESSFUL
Total time: 0 seconds

Apache Ant Tasks – Move

Description

Move task moves a file to a new file or directory, or collections of files to a new directory. By default, the destination file is overwritten if it already exists. When overwrite is turned off, then files are only moved if the source file is newer than the destination file, or when the destination file does not exist.

Properties




















Sr.No Attributes & Description
1

File

The file or directory to move.

2

Preservelastmodified

Give the moved files the same last modified time as the original source files.

3

Tofile

The file to move to.

4

Todir

The directory to move to.

5

Overwrite

Overwrite existing files even if the destination files are newer.

6

Force

Overwrite read-only destination files.

7

Filtering

Indicates whether token filtering should take place during the move.

8

Flatten

Ignore directory structure of source directory, copy all files into a single directory, specified by the todir attribute.

9

IncludeEmptyDirs

Copy empty directories included with the nested FileSet(s).

10

Failonerror

If false, log a warning message, but do not stop the build, when the file to copy does not exist or one of the nested filesets points to a directory that doesn”t exist or an error occurs while moving.

11

Quiet

If true and failonerror is false, then do not log a warning message when the file to copy does not exist or one of the nested filesets points to a directory that doesn”t exist or an error occurs while copying.

12

Verbose

Log the files that are being moved.

13

Encoding

The encoding to assume when filter-copying the files.

14

Outputencoding

The encoding to use when writing the files.

15

Enablemultiplemappings

If true the task will process to all the mappings for a given source path. If false the task will only process the first file or directory. This attribute is only relevant if there is a mapper subelement.

16

Granularity

The number of milliseconds leeway to give before deciding a file is out of date. This is needed because not every file system supports tracking the last modified time to the millisecond level. This can also be useful if source and target files live on separate machines with clocks being out of sync.

17

performGCOnFailedDelete

If Ant fails to delete a file or directory it will retry the operation once. If this flag is set to true it will perform a garbage collection before retrying the delete. Setting this flag to true is known to resolve some problems on Windows (where it defaults to true) but also for directory trees residing on an NFS share.

Example

Usage

Create build.xml with the following content −


<?xml version="1.0"?>
<project name="TutorialPoint" default="info">
   <target name="info">
      <move file="message.txt" tofile="message.txt.moved"/>
   </target>
</project>

Output

Running Ant on the above build file produces the following output −


F:tutorialspointant>ant
Buildfile: F:tutorialspointantbuild.xml

info:
   [move] Moving 1 file to F:tutorialspointant

BUILD SUCCESSFUL
Total time: 0 seconds

Apache Ant Tasks – Sleep

Description

Sleep task is for sleeping a short period of time, useful when a build or deployment process requires an interval between tasks.

Properties








Sr.No Attributes & Description
1

Hours

Hours to add to the sleep time.

2

Minutes

Minutes to add to the sleep time.

3

Seconds

Seconds to add to the sleep time.

4

Milliseconds

Milliseconds to add to the sleep time.

5

Failonerror

Flag controlling whether to break the build on an error.

Example

Usage

Create build.xml with the following content −


<?xml version="1.0"?>
<project name="TutorialPoint" default="info">
   <target name="info">
      <sleep seconds="2"/>
   </target>
</project>

Output

Running Ant on the above build file produces the following output −


F:tutorialspointant>ant
Buildfile: F:tutorialspointantbuild.xml

info:

BUILD SUCCESSFUL
Total time: 2 seconds

Apache Ant Tasks – WAR

Description

War task is an extension of the Jar task with special treatment for files that should end up in the WEB-INF/lib, WEB-INF/classes or WEB-INF directories of the Web Application Archive.

Properties


































Sr.No Attributes & Description
1

Destfile

The WAR file to create.

2

Webxml

The servlet configuration descriptor to use (WEB-INF/web.xml).

3

Basedir

The directory from which to jar the files.

4

Compress

Not only store data but also compress them. Unless you set the keepcompression attribute to false, this will apply to the entire archive, not only the files you”ve added while updating.

5

Keepcompression

For entries coming from existing archives (like nested zipfilesets or while updating the archive), keep the compression as it has been originally instead of using the compress attribute.

6

Encoding

The character encoding to use for filenames inside the archive.

7

Filesonly

Store only file entries.

8

Include

comma- or space-separated list of patterns of files that must be included.

9

includesfile

Name of a file. Each line of this file is taken to be an include pattern.

10

Excludes

comma- or space-separated list of patterns of files that must be excluded.

11

Excludesfile

Name of a file. Each line of this file is taken to be an exclude pattern.

12

defaultexcludes

Indicates whether default excludes should be used or not (yes|no).

13

Menifest

The manifest file to use.

14

Filesetmanifest

Behavior when a manifest file is found in a zipfileset or zipgroupfileset file. Valid values are skip, merge, and mergewithoutmain. merge will merge all of the manifests together, and merge this into any other specified manifests. mergewithoutmain merges everything but the Main section of the manifests.

15

Whenmanifestonly

Behavior when no files match. Valid values are fail, skip, and create.

16

Manifestencoding

The encoding used to read the JAR manifest, when a manifest file is specified.

17

Index

Whether to create an index list to speed up classloading. Unless you specify additional jars with nested indexjars elements, only the contents of this jar will be included in the index.

18

indexMetaInf

Whether to include META-INF and its children in the index. Doesn”t have any effect if index is false. Oracle”s jar implementation used to skip the META-INF directory and Ant followed that example. The behavior has been changed with Java 5. In order to avoid problems with Ant generated jars on Java 1.4 or earlier, Ant will not include META-INF unless explicitly asked to.

19

Manifestencoding

The encoding used to read the JAR manifest, when a manifest file is specified.

20

Update

Indicates whether to update or overwrite the destination file if it already exists.

21

Duplicate

Behavior when a duplicate file is found. Valid values are add, preserve, and fail.

22

Roundup

Whether the file modification times will be rounded up to the next even number of seconds.

23

Level

Non-default level at which file compression should be performed. Valid values range from 0 (no compression/fastest) to 9 (maximum compression/slowest).

24

preserve0permissions

When updating an archive or adding entries from a different archive Ant will assume that a Unix permissions value of 0 (nobody is allowed to do anything to the file/directory) means that the permissions haven”t been stored at all rather than real permissions and will instead apply its own default values.

25

useLanguageEncodingFlag

Whether to set the language encoding flag if the encoding is UTF-8. This setting doesn”t have any effect if the encoding is not UTF-8.

26

createUnicodeExtraFields

Whether to create Unicode extra fields to store the file names a second time inside the entry”s metadata.

27

fallbacktoUTF8

Whether to use UTF-8 and the language encoding flag instead of the specified encoding if a file name cannot be encoded using the specified encoding.

28

mergeClassPathAttributes

Whether to merge the Class-Path attributes found in different manifests (if merging manifests). If false, only the attribute of the last merged manifest will be preserved.

29

FlattenAttributes

Whether to merge attributes occurring more than once in a section (this can only happen for the Class-Path attribute) into a single attribute.

30

zip64Mode

When to use Zip64 extensions for entries. The possible values are never, always and as-needed.

31

Needxmlfile

Flag to indicate whether or not the web.xml file is needed. It should be set to false when generating servlet 2.5+ WAR files without a web.xml file.

Example

Usage

Create build.xml with the following content −


<?xml version="1.0"?>
<project name="TutorialPoint" default="info">
   <target name="info">
      <war destfile="myapp.war" webxml="web.xml"></war>
   </target>
</project>

Above script will create an ear file in the current directory as myapp.ear.

Output

Running Ant on the above build file produces the following output −


F:tutorialspointant>ant
Buildfile: F:tutorialspointantbuild.xml

info:
   [war] Building war: F:tutorialspointantmyapp.war

BUILD SUCCESSFUL
Total time: 1 second

Apache Ant Tasks – Zip

Description

zip task creates a zip file.

Properties

































Sr.No Attributes & Description
1

Destfile

The ZIP file to create.

2

Zipfile

Old name of destfile. Deprecated.

3

Basedir

The directory from which to jar the files.

4

Compress

Not only store data but also compress them. Unless you set the keepcompression attribute to false, this will apply to the entire archive, not only the files you”ve added while updating.

5

Keepcompression

For entries coming from existing archives (like nested zipfilesets or while updating the archive), keep the compression as it has been originally instead of using the compress attribute.

6

Encoding

The character encoding to use for filenames inside the archive.

7

Filesonly

Store only file entries.

8

Include

comma- or space-separated list of patterns of files that must be included.

9

Includesfile

name of a file. Each line of this file is taken to be an include pattern.

10

Excludes

comma- or space-separated list of patterns of files that must be excluded.

11

Excludesfile

Name of a file. Each line of this file is taken to be an exclude pattern.

12

Defaultexcludes

Indicates whether default excludes should be used or not (yes|no).

13

Menifest

The manifest file to use.

14

Filesetmanifest

Behavior when a manifest file is found in a zipfileset or zipgroupfileset file. Valid values are skip, merge, and mergewithoutmain. merge will merge all of the manifests together, and merge this into any other specified manifests. mergewithoutmain merges everything but the Main section of the manifests.

15

Whenmanifestonly

Behavior when no files match. Valid values are fail, skip, and create.

16

Manifestencoding

The encoding used to read the JAR manifest, when a manifest file is specified.

17

Index

Whether to create an index list to speed up classloading. Unless you specify additional jars with nested indexjars elements, only the contents of this jar will be included in the index.

18

indexMetaInf

Whether to include META-INF and its children in the index. Doesn”t have any effect if index is false. Oracle”s jar implementation used to skip the META-INF directory and Ant followed that example. The behavior has been changed with Java 5. In order to avoid problems with Ant generated jars on Java 1.4 or earlier, Ant will not include META-INF unless explicitly asked to.

19

Manifestencoding

The encoding used to read the JAR manifest, when a manifest file is specified.

20

Update

Indicates whether to update or overwrite the destination file if it already exists.

21

Duplicate

Behavior when a duplicate file is found. Valid values are add, preserve, and fail.

22

Roundup

Whether the file modification times will be rounded up to the next even number of seconds.

23

Level

Non-default level at which file compression should be performed. Valid values range from 0 (no compression/fastest) to 9 (maximum compression/slowest).

24

Preserve0permissions

When updating an archive or adding entries from a different archive Ant will assume that a Unix permissions value of 0 (nobody is allowed to do anything to the file/directory) means that the permissions haven”t been stored at all rather than real permissions and will instead apply its own default values.

25

useLanguageEncodingFlag

Whether to set the language encoding flag if the encoding is UTF-8. This setting doesn”t have any effect if the encoding is not UTF-8.

26

createUnicodeExtraFields

Whether to create Unicode extra fields to store the file names a second time inside the entry”s metadata.

27

FallbacktoUTF8

Whether to use UTF-8 and the language encoding flag instead of the specified encoding if a file name cannot be encoded using the specified encoding.

28

mergeClassPathAttributes

Whether to merge the Class-Path attributes found in different manifests (if merging manifests). If false, only the attribute of the last merged manifest will be preserved.

29

flattenAttributes

Whether to merge attributes occurring more than once in a section (this can only happen for the Class-Path attribute) into a single attribute.

30

Zip64Mode

When to use Zip64 extensions for entries. The possible values are never, always and as-needed.

Example

Usage

Create build.xml with the following content −


<?xml version="1.0"?>
<project name="TutorialPoint" default="info">
   <target name="info">
      <zip basedir="src" destfile="src.zip" />
      <echo>src archived.</echo>
   </target>
</project>

Output

Create a text.txt file with some content in the same folder. Now running Ant on the above build file produces the following output −


F:tutorialspointant>ant
Buildfile: F:tutorialspointantbuild.xml

info:
   [zip] Building zip: F:tutorialspointantsrc.zip
   [echo] src archived.

BUILD SUCCESSFUL
Total time: 0 seconds

You can verify that the src.zip file created.

Apache Ant Tasks – JAR

Description

Jar task jars a set of file.

Properties
































Sr.No Attributes & Description
1

Destfile

The JAR file to create.

2

Basedir

The directory from which to jar the files.

3

Compress

Not only store data but also compress them. Unless you set the keepcompression attribute to false, this will apply to the entire archive, not only the files you”ve added while updating.

4

Keepcompression

For entries coming from existing archives (like nested zipfilesets or while updating the archive), keep the compression as it has been originally instead of using the compress attribute.

5

Encoding

The character encoding to use for filenames inside the archive.

6

Filesonly

Store only file entries.

7

Include

comma- or space-separated list of patterns of files that must be included.

8

Includesfile

Name of a file. Each line of this file is taken to be an include pattern.

9

Excludes

comma- or space-separated list of patterns of files that must be excluded.

10

Excludesfile

Name of a file. Each line of this file is taken to be an exclude pattern.

11

Defaultexcludes

Indicates whether default excludes should be used or not (yes|no).

12

Menifest

The manifest file to use.

13

Filesetmanifest

Behavior when a manifest file is found in a zipfileset or zipgroupfileset file. Valid values are skip, merge, and mergewithoutmain. merge will merge all of the manifests together, and merge this into any other specified manifests. mergewithoutmain merges everything but the Main section of the manifests.

14

Whenmanifestonly

Behavior when no files match. Valid values are fail, skip, and create.

15

Manifestencoding

The encoding used to read the JAR manifest, when a manifest file is specified.

16

Index

Whether to create an index list to speed up classloading. Unless you specify additional jars with nested indexjars elements, only the contents of this jar will be included in the index.

17

indexMetaInf

Whether to include META-INF and its children in the index. Doesn”t have any effect if index is false. Oracle”s jar implementation used to skip the META-INF directory and Ant followed that example. The behavior has been changed with Java 5. In order to avoid problems with Ant generated jars on Java 1.4 or earlier, Ant will not include META-INF unless explicitly asked to.

18

Manifestencoding

The encoding used to read the JAR manifest, when a manifest file is specified.

19

Update

Indicates whether to update or overwrite the destination file if it already exists.

20

Duplicate

Behavior when a duplicate file is found. Valid values are add, preserve, and fail.

21

Roundup

Whether the file modification times will be rounded up to the next even number of seconds.

22

Level

Non-default level at which file compression should be performed. Valid values range from 0 (no compression/fastest) to 9 (maximum compression/slowest).

23

preserve0permissions

When updating an archive or adding entries from a different archive Ant will assume that a Unix permissions value of 0 (nobody is allowed to do anything to the file/directory) means that the permissions haven”t been stored at all rather than real permissions and will instead apply its own default values.

24

useLanguageEncodingFlag

Whether to set the language encoding flag if the encoding is UTF-8. This setting doesn”t have any effect if the encoding is not UTF-8.

25

createUnicodeExtraFields

Whether to create Unicode extra fields to store the file names a second time inside the entry”s metadata.

26

fallbacktoUTF8

Whether to use UTF-8 and the language encoding flag instead of the specified encoding if a file name cannot be encoded using the specified encoding.

27

mergeClassPathAttributes

Whether to merge the Class-Path attributes found in different manifests (if merging manifests). If false, only the attribute of the last merged manifest will be preserved.

28

flattenAttributes

Whether to merge attributes occurring more than once in a section (this can only happen for the Class-Path attribute) into a single attribute.

29

zip64Mode

When to use Zip64 extensions for entries. The possible values are never, always and as-needed.

Example

Usage

Create build.xml with the following content −


<?xml version="1.0"?>
<project name="TutorialPoint" default="info">
   <target name="info">
      <jar basedir="app" destfile="app.jar" />
      <echo>jar created.</echo>
   </target>
</project>

Above script will create an ear file in the current directory as myapp.ear.

Output

Running Ant on the above build file produces the following output −


F:tutorialspointant>ant
Buildfile: F:tutorialspointantbuild.xml

info:
   [jar] Building jar: F:tutorialspointantapp.jar
   [echo] jar created.

BUILD SUCCESSFUL
Total time: 0 seconds

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *