Apache Ant Tasks 简明教程

Apache Ant Tasks - Quick Guide

Apache Ant Tasks - Introduction

ANT 代表 Another Neat 工具。它是一种来自计算机软件开发公司 Apache 的基于 Java 的构建工具。在深入了解 Apache Ant 的细节之前,让我们首先理解为什么我们需要一个构建工具。

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 −

  1. Compiling the code

  2. Packaging the binaries

  3. Deploying the binaries to the test server

  4. Testing the changes

  5. Copying the code from one location to another

Apache Ant 对于自动化和简化上述任务非常有用。它是一种可以从命令行执行的操作系统构建和部署工具。Ant 任务简化了操作的执行。

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 最初是由软件开发人员 James Duncan Davidson 创建的,他也是 web 服务器应用程序 Tomcat 的最初创建者。

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

Ant 最初用于构建 Tomcat,并作为 Tomcat 发行版的一部分进行捆绑。

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

它的诞生源于与 Apache Make 工具相关的复杂性和问题。

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

它于 2000 年作为 Apache 中的一个独立项目进行了推广。截至 2021 年 10 月,Apache Ant 的最新版本为 1.10.12

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

Apache Ant 的功能如下所示 −

The features of Apache Ant are listed below −

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

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

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

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

  5. Ant is good at automating complicated repetitive tasks.

  6. Ant comes with a big list of predefined tasks.

  7. Ant provides an interface to develop custom tasks.

  8. 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 以 Apache 软件许可证分发,该许可证是开源计划认证的、成熟的开源许可证。

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

最新版本的 Apache Ant, 包括了它的全源代码、类文件和文档,可以在 https://ant.apache.org 找到。

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

我们假设您已经下载并安装了 Java 开发工具包 (JDK)。如果没有,请按照 file:///C:/java/java_environment_setup.htm 的说明进行操作。

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

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

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

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

  4. 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.

  5. 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-bin\bin folder.

Verifying the Installation

在计算机中验证 Apache Ant 的安装是否成功,请在命令提示符中键入 ant。

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

本教程还涵盖了 Ant 和 Eclipse 集成开发环境 (IDE) 的集成。因此,如果您没有安装 Eclipse,请下载并安装 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

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

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

  3. Run Eclipse from c:\eclipse\eclipse.exe.

Apache Ant Tasks - BaseName

Description

Basename 任务确定指定文件/目录的基本名称,同时移除通过的后缀(如果已通过)。如果是文件的完整路径,则使用文件的名称。如果是目录路径,则使用最后一个目录的名称。

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

使用以下内容创建 build.xml −

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

在上述构建文件上运行 Ant 会生成以下输出:

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

F:\tutorialspoint\ant>ant
Buildfile: F:\tutorialspoint\ant\build.xml

info:
   [echo] application

BUILD SUCCESSFUL
Total time: 0 seconds

Apache Ant Tasks - GZip

Description

Gzip 任务基于 GZip、BZip2 或 XZ 算法创建存档。仅当它不存在或者源文件较新时才会生成输出文件。

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

使用以下内容创建 build.xml:

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

在同一文件夹中创建包含一些内容的 text.txt 文件。现在在上述构建文件上运行 Ant 会产生以下输出 −

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:\tutorialspoint\ant>ant
Buildfile: F:\tutorialspoint\ant\build.xml

info:
     [gzip] Building: F:\tutorialspoint\ant\text.gz
     [echo] File archived.

BUILD SUCCESSFUL
Total time: 0 seconds

你可以验证已创建 text.gz 文件。

You can verify that the text.gz file created.

Apache Ant Tasks - GUnzip

Description

Gunzip 任务使用 GZip、BZip2 或 XZ 算法提取存档。仅当输出文件不存在或源资源较新时才会生成输出文件。如果省略 dest,则使用 src 的父目录。

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

使用以下内容创建 build.xml:

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

让我们将 text.gz 文件解压缩至 text.txt。现在在上面的构建文件中运行 Ant,将生成以下输出 −

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

F:\tutorialspoint\ant>ant
Buildfile: F:\tutorialspoint\ant\build.xml

info:
   [gunzip] Expanding text.gz to F:\tutorialspoint\ant\text.txt
   [echo] File extracted.

BUILD SUCCESSFUL
Total time: 0 seconds

你可以验证已经创建了 text.txt 文件。

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

Apache Ant Tasks - Chmod

Description

Chmod 任务在 Unix 中运行,并且工作方式与 chmod 命令相似。它会更改文件或指定目录中所有文件的权限。

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

Example

Usage

使用以下内容创建 build.xml −

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>

上面的脚本使 start.sh 在 Unix 机器上可读且可执行。

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

Apache Ant Tasks - Concat

Description

Concat 任务将一个或多个资源连接到单个文件或控制台。如果目标文件不存在,则创建该文件,除非资源列表为空且 ignoreempty 标志为 true。

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

使用以下内容创建 build.xml −

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>

上述脚本将读取 messages 文件夹并在名称中具有 test 的文件的连接内容显示在控制台上。

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

Output

我们在 messages 文件夹中使用内容“Welcome to tutorialspoint.com”创建 test.txt。现运行上述构建文件中的 Ant 会生成以下输出 −

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:\tutorialspoint\ant>ant
Buildfile: F:\tutorialspoint\ant\build.xml

info:
   [concat] Welcome to tutorialspoint.com

BUILD SUCCESSFUL
Total time: 0 seconds

Apache Ant Tasks - Condition

Description

条件任务在条件为 true 时默认将属性值设置为 true;否则,属性未设置。可以通过指定 value 属性将值设置为非默认值。

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

使用以下内容创建 build.xml −

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>

上面的脚本将基于底层操作系统是否为 Windows,设置一个变量 is Windows。

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

Output

在上述构建文件上运行 Ant 会生成以下输出:

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

F:\tutorialspoint\ant>ant
Buildfile: F:\tutorialspoint\ant\build.xml

info:
   [echo] true

BUILD SUCCESSFUL
Total time: 0 seconds

Apache Ant Tasks - Copy

Description

Copy 任务将文件/资源集合复制到新文件或目录中。仅当源文件比目标文件新或目标文件不存在时,才复制文件。

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

使用以下内容创建 build.xml −

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>

上面的脚本会在当前目录中将一个名为 text.txt 的文件复制为 textcopy.txt

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

Output

在上述构建文件上运行 Ant 会生成以下输出:

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

F:\tutorialspoint\ant>ant
Buildfile: F:\tutorialspoint\ant\build.xml

info:
   [echo] Copying 1 file to F:\tutorialspoint\ant

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

使用以下内容创建 build.xml −

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

在上述构建文件上运行 Ant 会生成以下输出:

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

F:\tutorialspoint\ant>ant
Buildfile: F:\tutorialspoint\ant\build.xml

info:
   [delete] Deleting: F:\tutorialspoint\ant\text.txt

BUILD SUCCESSFUL
Total time: 0 seconds

Apache Ant Tasks - EAR

Description

Ear 任务是对 Jar 任务的扩展,对应该最终出现在 Enterprise 应用存档中的文件采取特殊处理。

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

Example

Usage

使用以下内容创建 build.xml −

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>

上述脚本将在当前目录中创建一个名为 myapp.ear 的 ear 文件。

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

Output

在上述构建文件上运行 Ant 会生成以下输出:

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

F:\tutorialspoint\ant>ant
Buildfile: F:\tutorialspoint\ant\build.xml

info:
   [ear] Building ear: F:\tutorialspoint\ant\build\myapp.ear

BUILD SUCCESSFUL
Total time: 1 second

Apache Ant Tasks - Fail

Description

错误任务用于通过引发 BuildException 来退出当前构建,可以选择性地打印其他信息。可以通过 message 属性或嵌套到元素中的字符数据设置异常消息。

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

使用以下内容创建 build.xml −

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>

上面的脚本将使构建失败,因为未设置 src.dir。

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

Output

在上述构建文件上运行 Ant 会生成以下输出:

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

F:\tutorialspoint\ant>ant
Buildfile: F:\tutorialspoint\ant\build.xml

info:

BUILD FAILED
F:\tutorialspoint\ant\build.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

使用以下内容创建 build.xml −

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>

以及嵌套的 xml 文件,内容如下 −

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>

上述脚本将在当前目录中创建一个名为 myapp.ear 的 ear 文件。

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

Output

在上述构建文件上运行 Ant 会生成以下输出:

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

F:\tutorialspoint\ant>ant
Buildfile: F:\tutorialspoint\ant\build.xml

setUp:

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

info:

BUILD SUCCESSFUL
Total time: 0 seconds

Apache Ant Tasks - Java

Description

Java 任务在运行的 JVM 内执行一个 Java 类,或如果使用 fork=true 指明,则分叉到另一个 JVM;

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

使用以下内容创建 TestMessage.java −

Create TestMessage.java with the following content −

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

使用以下内容创建 build.xml −

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>

以上脚本将运行一个 java 类文件以打印输出。

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

Output

在上述构建文件上运行 Ant 会生成以下输出:

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

F:\tutorialspoint\ant>ant
Buildfile: F:\tutorialspoint\ant\build.xml

info:
   [java] Welcome to tutorialspoint.com

BUILD SUCCESSFUL
Total time: 0 seconds

Apache Ant Tasks - Javac

Description

Javac 任务编译 Java 源树。将递归扫描源目录和目标目录,以查找要编译的 Java 源文件。只有对应 .class 文件不存在或 .class 文件较旧的 .java 文件才会被编译。

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

Example

Usage

在 src 目录中创建 TestMessage.java,其内容如下:

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");
   }
}

使用以下内容创建 build.xml:

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>

以上脚本将运行一个 java 类文件以打印输出。

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

Output

在上述构建文件上运行 Ant 会生成以下输出:

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

F:\tutorialspoint\ant>ant
Buildfile: F:\tutorialspoint\ant\build.xml

info:
   [javac] F:\tutorialspoint\ant\build.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:\tutorialspoint\ant\build

BUILD SUCCESSFUL
Total time: 0 seconds

Apache Ant Tasks - Length

Description

Length 任务显示或设置一个包含字符串、文件或一个或多个嵌套资源集合的长度信息的属性。它也可以用作条件。

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

使用以下内容创建 build.xml −

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

在上述构建文件上运行 Ant 会生成以下输出:

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

F:\tutorialspoint\ant>ant
Buildfile: F:\tutorialspoint\ant\build.xml

info:
   [echo] 14

BUILD SUCCESSFUL
Total time: 0 seconds

Apache Ant Tasks - LoadFile

Description

Loadfile 任务将载入文件并将内容设置为属性。

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

使用以下内容创建 message.txt −

Create message.txt with the following content −

Welcome to tutorialspoint.com

Example

使用以下内容创建 build.xml −

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

在上述构建文件上运行 Ant 会生成以下输出:

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

F:\tutorialspoint\ant>ant
Buildfile: F:\tutorialspoint\ant\build.xml

info:
   [echo] Welcome to tutorialspoint.com

BUILD SUCCESSFUL
Total time: 0 seconds

Apache Ant Tasks - MkDir

Description

Mkdir 任务创建目录。在必要时也创建不存在的父目录。如果目录已经存在,则不执行任何操作。

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

使用以下内容创建 build.xml −

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

在上述构建文件上运行 Ant 会生成以下输出:

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

F:\tutorialspoint\ant>ant
Buildfile: F:\tutorialspoint\ant\build.xml
   [mkdir] Created dir: F:\tutorialspoint\ant\dist

info:

BUILD SUCCESSFUL
Total time: 0 seconds

Apache Ant Tasks - Move

Description

Move 任务将文件移动到新文件或目录中,或将文件集合移动到新目录中。默认情况下,如果目标文件已存在,则会覆盖该文件。当 overwrite 关闭时,只有源文件比目标文件更新时或当目标文件不存在时,才会移动文件。

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

使用以下内容创建 build.xml −

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

在上述构建文件上运行 Ant 会生成以下输出:

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

F:\tutorialspoint\ant>ant
Buildfile: F:\tutorialspoint\ant\build.xml

info:
   [move] Moving 1 file to F:\tutorialspoint\ant

BUILD SUCCESSFUL
Total time: 0 seconds

Apache Ant Tasks - Sleep

Description

Sleep 任务用于在短时间内休眠,当构建或部署过程需要在任务之间设置时间间隔时,此任务非常有用。

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

使用以下内容创建 build.xml −

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

在上述构建文件上运行 Ant 会生成以下输出:

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

F:\tutorialspoint\ant>ant
Buildfile: F:\tutorialspoint\ant\build.xml

info:

BUILD SUCCESSFUL
Total time: 2 seconds

Apache Ant Tasks - WAR

Description

War 任务是 Jar 任务的扩展,专门针对最终应位于 Web 应用程序归档的 WEB-INF/lib、WEB-INF/classes 或 WEB-INF 目录中的文件进行处理。

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

Example

Usage

使用以下内容创建 build.xml −

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>

上述脚本将在当前目录中创建一个名为 myapp.ear 的 ear 文件。

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

Output

在上述构建文件上运行 Ant 会生成以下输出:

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

F:\tutorialspoint\ant>ant
Buildfile: F:\tutorialspoint\ant\build.xml

info:
   [war] Building war: F:\tutorialspoint\ant\myapp.war

BUILD SUCCESSFUL
Total time: 1 second

Apache Ant Tasks - Zip

Description

zip 任务创建 zip 文件。

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

Example

Usage

使用以下内容创建 build.xml −

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

在同一文件夹中创建包含一些内容的 text.txt 文件。现在在上述构建文件上运行 Ant 会产生以下输出 −

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:\tutorialspoint\ant>ant
Buildfile: F:\tutorialspoint\ant\build.xml

info:
   [zip] Building zip: F:\tutorialspoint\ant\src.zip
   [echo] src archived.

BUILD SUCCESSFUL
Total time: 0 seconds

您可以验证 src.zip 文件是否创建。

You can verify that the src.zip file created.

Apache Ant Tasks - JAR

Description

Jar 任务将一组文件打包成 jar 包。

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

Example

Usage

使用以下内容创建 build.xml −

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>

上述脚本将在当前目录中创建一个名为 myapp.ear 的 ear 文件。

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

Output

在上述构建文件上运行 Ant 会生成以下输出:

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

F:\tutorialspoint\ant>ant
Buildfile: F:\tutorialspoint\ant\build.xml

info:
   [jar] Building jar: F:\tutorialspoint\ant\app.jar
   [echo] jar created.

BUILD SUCCESSFUL
Total time: 0 seconds