ANT information

xiaoxiao2021-03-06  101

Compiling source code Since Ant's main goal is to generate Java applications, it can support call Javac compiler and other inner, excellent

Java related tasks is not surprising. Below is a writing method for compiling Java code: This tag is looking for all files in the src directory to extension, and call the Javac compiler to the same

Generate class files in the catalog. Of course, placing class files in a separate directory structure is generally clearer; can be added to Destdir

Attributes let Ant do this. Other useful properties include:

ClassPath: Equivalent to the -classpath option for Javac. Debug = "true": Indicates the compiler to compile the source file with the debug information. An important feature of the Javac mission is that it only compiles the source files it thinks need to be compiled. If a class file already exists,

And the corresponding source file has not changed since the class of file generation, then the source file will not be recompiled. Javac mission

The output shows the number of source files actually compiled. Write a Clean target to remove the generated file from the target directory is

A good habit. You can use this task if you want to make sure all source files are compiled. This behavior portrayed a lot of Ant

The characteristics of the task: If a task can determine that the requested operation does not need to be executed, then the action will be skipped.

Like Ant, the Javac compiler itself is also implemented in Java language. This is very important for the use of Javac tasks in Ant

It is advantageous because it typically invokes the compiler class in the same Java virtual machine (JVM) in the ANT run. Each time you need to compile Java

Other generation tools typically need a new JVM instance to run a new Java process. But use

In the case of Ant, only a single JVM instance is required, which is used to run the ANT itself, also used to perform all the necessary compilation tasks (

And other related tasks, such as processing JAR files). This is a much efficient resource usage, which can greatly shorten the project generation.

time.

Compiler option

As we see from the previous section, the default behavior of Ant's Javac mission is to call any JVM of the ANT itself.

The translation. However, sometimes you may want to call the compiler separately - for example, when you want to specify some memory options for the compiler, or

It is necessary to use a different level of compiler. To achieve this, simply set the Javac's fork property to true.

For example, like this:

If you want to specify a different Javac executable and pass a maximum memory setting to it, you can do this below:

You can even configure Ant to use a different compiler. Supported compilers include the JIKES compiler of open source code and come

The GCI compiler of the GNU compiler set (GNU Compiler Collection, GCC). (Please refer to the reference information for this

More information for both compilers. ) These compilers can be specified in two ways: You can set the build.Compiler property, which will be applied to all occasions of the Javac task; or set the Compiler property in each Javac task as needed.

The Javac task also supports many other options. Please refer to the ANT manual for more details (see Resources).

Create a JAR file

Create JAR File Page 4 (6 pages of)

After compiling the Java source file, the result class file is usually packaged into a JAR file, this file is similar to the ZIP archive.

Each JAR file contains a manifest file that specifies the properties of the JAR file.

Below is a simple usage example of the JAR task in Ant:

This will create a JAR file called package.jar and add all the files in the classes directory (JAR file)

Ability to include any type of file, not just a class file). There is no specified manifest file here, so Ant will provide a basic clear

Single file.

The Manifest property allows you to specify a file that is used as the JAR file. Manifest can be used in the content of the list file.

Try to specify in the generated file. This task can write a manifest file like a file system, or can actually nested within JAR,

Create a list file and JAR files one-time. E.g:

Generate timestamp

Use the current time and date in the generated environment to mark the output of a generated task in some way so that it is generated,

This is often desirable. This may involve editing a file in order to insert a string to specify the date and time, or combine this information.

And in the file name of the JAR or ZIP file.

This needs is solved by simple but very useful TSTAMP tasks. This task usually calls at a certain generation process.

For example, in an init goal. This task does not require attributes, and only is enough in many cases.

TSTAMP does not produce any output; in contrast, it sets the ANT attribute based on the current system time and date. Here is a TSTAMP setting

Examples of the values ​​of each attribute, the description of each attribute, and these attributes can be set:

Attribute Description Example DSTAMP is set to the current date, the default format is set to the current time, the default format is HHMM 1603 Today set to the current date, with a complete month December 17, 2003

For example, in the previous section, we created a JAR file as follows:

After calling the TSTAMP task, we can name the JAR file based on the date, as shown below:

Therefore, if this task is called on December 17, 2003, the JAR file will be named package-20031217.jar.

You can also configure TSTAMP tasks to set different properties, apply a time-offset before or after a current time, or different parties

Format this string. All of this is done using a nested Format element, as shown below:

The above list sets the OFFSET_TIME attribute to the number of hours, minutes and seconds of the distance after 10 minutes.

The characters used to define the format string are the same as those defined by the Java.Text.SIMPLEDATEFORMAT class.

Integrate

As a few sections provide us with sufficient knowledge required to generate a simple Java project. Here, these code snippets will be combined into a complete

Generate file, it will compile all source code in the src directory, put the result class file in the build directory, then put all types of texts

Pack into a JAR file in the dist directory. To test this generated file, what you need is to include one or more

The SRC directory of the Java source code - this directory can contain a simple "Hell World" program from a certain existing term.

The purpose of a large amount of source files. If you need to add JAR files or anything else to Java ClassPath, in order to succeed

To compile the source code, you only need to add a ClassPath property to it in the Javac task.

The generated file looks as follows:

a Simple java project < Property name = "builddir" location = "build" /> The following is to use this file Example of a certain generation process (you get the output may not be the same, depending on the src directory

content):

Buildfile: build.xmlinit: [mkdir] Created dir: E: / tutorial / javaexample / build [mkdir] Created dir: E: / tutorial / javaexample / distcompile: [javac] Compiling 10 source files to E: / tutorial / javaexample / builddist: [jar] Building jar: E: /tutorial/javaexample/dist/package-20031217.jar [jar] Building jar: E: /tutorial/javaexample/dist/package-src-20031217.jarBUILD SUCCESSFULTotal time: 5 seconds Note The JAR file is named according to the current date and sets a list entry for the primary class of the application so that the main class can pass.

A simple command java -jar package-20031217.jar is running directly. We also created a JAR file, it only

Contains the source code of the project.

File Operating System We understand enough knowledge about Ant, now able to generate a basic Java project, but the actual project is of course

I rarely like our examples. In the following sections, we will examine a number of additional features of Ant, and

Use them.

In this section, we will examine how to perform common file operations, such as creating a directory and decompress file. One of the excellent features of Ant lies in

The task of performing these operations is usually the same on all platforms.

Create and delete a directory

One of the most basic file system operations is to create a directory or folder. The task of doing this work is MKDIR, it is not surprising, it is very

Similar to Windows and UNIX / Linux commands with the same name.

First pay attention to / being used as a directory separator, which is a formula for UNIX and Linux. You may think this is not very platform-independent, but

Is ANT knows how to handle it, and do the right thing for the platform where it is running, this is the location-based attribute

The way you see is the same. We can use it as it is easy to use /, regardless of the platform - Ant can handle any form

And even two forms of mixing can be handled.

Another useful feature of the MKDIR task is its ability to create them when the parent directory does not exist. Consider the above list,

Imagine the Archive directory exists, but the Metals directory does not exist. If you use the mkdir command of the underlying platform, you need to show first

Create a Metals directory, then call the mkdir command for the second time to create a zinc directory. But Ant tasks are more intelligent than this

It can create these two directories one-time. Similarly, if the target directory already exists, the MKDIR task will not issue an error message, and

Just assume that its work has been completed, so nothing.

The delete directory is also very easy:

This will delete the specified directory along with all the files it contains and the subdirectory. Use the file attribute instead of the DIR property, you can specify you want to delete

Single file except.

Copy and mobile files

A copy of the copy of the document in Ant is simple. E.g:

You can also use Move to perform renamed operations instead of copying files:

Another common file system operation is to copy or move files to another. Ant syntax to do this work is also very simple:

By default, Ant only outputs a summary of the mobile and replication operations it performs, including information such as files that have been moved or copied.

. If you want to see more detailed information, including the file name involved, you can set the Verbose property to true.

Create and extract ZIP and TAR files

In the previous section, we saw how to create a JAR file. The process of creating other archived files is almost identical. Here is to create ZIP

The ANT task of the file:

The same syntax can also be used to create a TAR file. You can also use Gzip and BZIP tasks to compress files. E.g:

Zipfile = "Output.tar.gz" />

Unzip and extract the files is also simple:

DEST = "extractdir" />

It is also possible to include OverWrite properties to control overlay behavior. The default setting is to override the entries in the archive file being extracted.

All existing files. The relevant task name is Untar, Unjar, Gunzip, and Bunzip2.

Replace the tag in the file

The last file system operation we will be in this section is a Replace task, which performs the lookup and replacement operations in the file. Token

The property specifies the string to look up, the value property specifies a new string, all instances of the logged mark string are replaced

For this new string. E.g:

The replacement will be performed in an appropriate location within the file itself. To provide more detailed output, you can set the summary property to True.

. This will result in the number of missing string instances that the task output is found and replaced.

Other useful tasks and technologies

Before examining custom tasks, we first introduce some useful features that have not been encountered. A large number of functions are included in the ANT standard.

So this is only selected for several of the most useful features. Mode matching and file selectors are powerful mechanisms, which greatly enhances

The function of some of our tasks have been seen; will generate task links and work with CVS knowledge base, which is discovered

Two major practical applications of mechanisms.

Pattern matches When you examine file system tasks, we use only files and directories separately named. However, performing those operations for a set of documents for a set of documents to perform operations, for example, all files ending in .java in a given directory. As equivalent DOS and

The UNIX command provides such a function, and Ant also provides such a function. This is done using wildcard characters: *, it hits

Associate zero or more characters; and? It only matches a character. Therefore, the mode of matching all files ending in .java is just

* .java.

You can also match the directory execution mode. For example, mode src * / *. Java will match all Java in any directory with SRC prefix

file. There is also another mode structure: **, which matches any number of directories. For example, mode ** / *. Java will match the current directory

All Java files are construed.

You can use the file system task to use mode, such as nested Fileset elements in a fairly consistent way. Previous, we use this

To copy a single file:

If we want to use a pattern, you can replace the File property as a fileset element as follows:

FileSet By default, FileSet contains all files in the specified src directory, so we use only Java files.

INCLUDE element. Similarly, we can add an Exclude element to another mode to potentially eliminate the incrude finger.

Set match. You can even specify multiple include and Exclude elements; this will get a set of files and directories, they contain

All matching items of the include mode, but excludes all matching items of the Exclude mode.

Note that there is a very useful fileset feature, but this feature occasionally confuses for those who don't realize it.

This feature is called the default exclusion: the built-in mode list that is automatically excluded from the fileset content. This list includes directory named CVS

Matching entries, as well as files ending with ~ characters, they may be a backup file. You usually don't want to include this in file system operations.

Class files and directories, so exclude these files are the default behavior. However, if you really choose all files and directories without an exception, you can

To set the defaultexcludes property of the file set to NO.

With the selector as we have seen, the file set is used to specify a set of files, and the content of this group can use the include and Exclude model.

Specialization. It is also possible to use include and Exclude to select files using include the special elements called the selector. Below is the Ant

A list of available core selectors:

SIZE: This selector is used to select a file according to the byte size of the file (unless you specify a different unit).

The attribute is used to set the properties of the comparison (LESS, more or Equal), and the value attribute defines each file to compare it.

Target size.

Contains: Only files containing a given text string (specified by the Text property) matches this selector. By default, the lookup operation is sensitive; add CaseSensitive = "no" can change the default settings.

FILENAME: Name property Specifies the mode of matching with the file name. It is essentially the same as the include element, as well as the designated

The Exclude element when Negate = "YES" is the same.

Present: Select the following file from the current directory structure: they have the same name as the files in the specified targetdir directory and

Relative directory structure.

Depend: This selector has the same effect as the Present selector, but the matching file is limited to Targetdir

The corresponding file in the location, those files that have been modified recently.

Date: This selector selects files based on its last modified date. The property specifies the properties of the comparison is Before, after or

Equal, datetime property specifies the date and time of comparison, this date and time has a given fixed format mm / dd / yyyy

HH: mm am_or_pm. Note that there is a built-in 2 second offset on the Windows platform to allow the underlying file system.

This can result in the number of files that exceed expectations. Allowed cyclone time can be changed using the granularity property (in milliseconds

Unit to specify).

Depth: This selector checks the number of structural hierarchies of each file. MIN and / or MAX properties are used to select a desired directory layer

Number of documents. You can also combine selectors by nesting one or more selectors in a selector container. The most commonly used selector container and only

Select all the files it contains all the selected files. Other Select Its containers include OR, NOT, NONE, and MAJORITY.

Below is an example of a file set, which selects only those that are more than 512 bytes and contain strings "Hello".

There are two ways to generate file links to generate different methods of generating large projects. One is to make a single generated file do everything; the other is to make high-level generation

The file calls other generated files to perform a specific task to divide the generated process into many smaller parts.

It is easy to use Ant tasks to call another ANT generation from an ANT generation. In a simple case, you can use

ANTFILE properties, only specify those generated files to be used, and Ant will generate the default target in the generated file. E.g:

Any attribute defined in the parent is defined by default to subconscious files, although this can be specified inheritall = "false"

avoid. It is also possible to pass the explicit attribute by using the Property element - even if INHERITALL is set to

FALSE, these properties are still applicable to subcounted files. This feature is suitable for use in incoming parameters to subconstructive files.

Let us consider an example. Here is a generated file we want to call:

(us It hasn't encountered an Echo task in front - it simply outputs a given message.)

Below is the second generated file called the first generation file, it also gives the first generated file to the Message property:

The output obtained by run the second generated file is as follows:

BUILDFILE: Build.xmlcallsub: showMessage: [echo] message = HT Buildbuild SuccessFultotal Time: 0 Seconds

Customize Ant using custom tasks

As we see from the aforementioned sections, Ant is very powerful, with many core tasks covering a wide range of functional sets. It still has many this

There is no additional task that is not introduced, plus many optional tasks that provide extensive additional features, and one as an Ant-Contrib project

Other tasks provided by divide; Finally, there are more information available to external available. Faced with all of Ant

These tasks, you seem to never need other tasks, but the real power of Ant is its easy scalability. In fact, it is precisely

It is this scalability to develop so many additional tasks.

There may be such an occasion, which is more appropriate to create a custom task in such an occasion. For example, suppose you created a command line

Tools to perform a particular action; this tool may be the right candidate for the task available to Ant (when the tool is using Java language)

This is the case when writing, although the tool is not necessarily written in Java language. ) Exterior to Ant using Exec task

Calling the tool (this will introduce dependencies, and make the generated files more difficult to use across different platforms), you can direct it directly

Merge into the generated file. It is also possible to make Ant's conventional file sets and wildcard matching features to customize tasks.

In this section, we will examine the construction process of a simple custom task. This task will perform order operations in the file in the file and will

Sorted rows are written to a new file.

Create a custom task Page 2 of 4

To achieve a simple custom task, what we need is to expand org.apache.tools.nt.task class, and rewrite

EXECUTE () method. Therefore, as the framework of the custom task as this file, we will prepare the following code: import org.apache.tools.ant.buildexception; import org.apache.tools.ant.task; public class filesorter Extends Task {// the Method Executing the Task Public Void Execute () THROWS BuildException {}}

Note We declare that the execute () method throws a buildexception exception. If this task has any mistakes, we will throw

This exception is to point out the fault to Ant.

Most tasks, whether it is a core task or a custom task, use properties to control their behavior. For this simple task, I

We need an attribute to specify files to be sorted, and another property is required to specify the output of the sorting content. We put these two attributes separately

Called with File and Tofile.

ANT makes it easy to support the properties in custom tasks. To this end, we only need to implement a method with special formatting names,

Ant can call this method using the value specified in the generated file. The name of this method needs to be set plus attributes.

Name, so in this example, we need a way to setfile () and settofile (). When Ant encounters generated files

When a property setting is set, it will find a method (called Setter method) with the appropriate name in the relevant task.

The properties in the generation file are specified as a string, so the parameters of our setter method can be a string. In this way

In the case where Ant will call our method after any properties referenced by the expansion value. But sometimes

We want to treat the value of the property as a different type. The sample task here is this situation, where the attribute value reference file system

The file is not just references any string. It can be easily done by declaring the method parameters as java.io.file types.

this point. Ant will accept the character string value of the attribute and interpret it as a file and pass it to our method. If the file is used

The relative path name is specified, and will be converted to an absolute path relative to the project base directory. Ant can perform similar to other types

Conversion, such as the Boolean and Int types. If you provide two ways with the same name but have different parameters, Ant will make

With more clear way, the file type will take precedence over string type.

Two setter methods that this custom task need is similar to:

// the setter for the "file" attribute public void setfile (file file) {} // the setter for the "tofile" attribute public void settofile (file tofile) {}

Implement Custom Tasks Page 3 (4 pages of)

Using the frame developed in the previous section, now we can complete this simple file sorting task:

Import java.io. *; import java.util. *; import org.apache.tools.ant.buildexception; import org.apache.tools.ant.task; / ** * a Simple Example Task to Sort A file * / public class FileSorter extends Task {private File file, tofile; // The method executing the task public void execute () throws BuildException {System.out.println ( "Sorting file =" file); try {BufferedReader from = new BufferedReader ( new FileReader (file)); BufferedWriter to = new BufferedWriter (new FileWriter (tofile)); List allLines = new ArrayList (); // read in the input file String line = from.readLine ();! while (line = null ) {AllLines.Add (line); line = from.readline ();} from.close (); // sort the list collections.sort (allLines); // Write out the sorted list for (Listiterator i = allLines. Listiterator (); i.hasnext () ;) {String s = (String) i.next (); to.write ();} to.close ();} to.close ();} catch (filenotfoundexception e) {throw new buildexception (e);} Catch (IOEXCEPTION E) {throw new buildexception (e);}} // the setter for the "file" attribute public void setfile (file file) {this.file = file;} // the setter for the "Tofile" Attribute Public void settofile (file tofile) {this.tofile = Tofile;}} Use custom tasks page 4 (4 pages of 4)

Now we have developed and compiled this custom task, and you can use it from the generated file.

Before you can call the custom task, we need to specify a name to define it and tell Ant to implement this task.

The information of the class file, as well as any ClassPath settings necessary to locate this class file. This is done using the taskdef task, as shown below:

Datual! You can now use this custom task like a core task using Ant. Here is a complete generated file

It shows the definition and usage of this custom task:

Now create an Input.txt file in the current working directory to test this custom task. E.g:

Hello thethis is a lineand here is another one

Below is the console output generated after running the above generation file:

Buildfile: build.xmlmain: [filesorter] sorting file = E: /TUTORAL/CUSTOM/INPUT.TXTBUILD SUCCESSFULTITOTAL TIME: 0 Seconds

Note that the relative path name of INPUT.TXT is converted into an absolute path name in the current directory. This is because we will setter

The parameters of the method are specified as java.io.file type instead of java.lang.string type.

Now look at whether this task is actually working. At this point, you should have created a file called output.txt in the same directory.

Contains the following:

And Here Is Another OneHello Therethis Is A Line

You can try to specify a non-existing input file to determine how this task is reported to the Ant Report "File Not Found" exception

.

Congratulations: You have now developed and used a custom Ant task! Creating more complex tasks will also involve many other respects,

References include links to further information sources to this topic.

转载请注明原文地址:https://www.9cbs.com/read-104978.html

New Post(0)