Apache ANT Basics
- ANT - Build Files
- ANT - Property Task
- ANT - Property Files
- ANT - Data Types
- ANT - Building Projects
- ANT - Build Documentation
- ANT - Creating JAR files
- ANT - Create WAR Files
- ANT - Packaging Applications
- ANT - Deploying Applications
Apache ANT Advanced
Apache ANT Useful Examples
- ANT - Using Token
- ANT - Using Command Line Arguments
- ANT - Using If Else arguments
- ANT - Custom Components
- ANT - Listeners and Loggers
Apache ANT Useful Resources
ANT - Custom Components
Ant allows to create and use custom components very easily. Custom Components can be created by implementing Condition, Selector, Filter etc. interfaces. Once a class is ready, we can use typedef to create the component within build.xml to be used under any target.
Syntax
First define a class as Ant custom component say TextSelector.java then in build.xml, define a selector.
<typedef name="text-selector" classname="TextSelector" classpath="."/>
Then use that component within a target.
<target name="copy">
<copy todir="${dest.dir}" filtering="true">
<fileset dir="${src.dir}">
<text-selector/>
</fileset>
</copy>
</target>
Example
Create TextSelector.java with the following content and put the same in same place as build.xml −
TextSelector.java
import java.io.File;
import org.apache.tools.ant.types.selectors.FileSelector;
public class TextFilter implements FileSelector {
public boolean isSelected(File b, String filename, File f) {
return filename.toLowerCase().endsWith(".txt");
}
}
Create a text1.txt and a text2.java in src directory. Target is to be copy only .txt file to build directory.
Create build.xml with the following content −
build.xml
<?xml version="1.0"?>
<project name="sample" basedir="." default="copy">
<property name="src.dir" value="src"/>
<property name="dest.dir" value="build"/>
<typedef name="text-selector" classname="TextSelector" classpath="."/>
<target name="copy">
<copy todir="${dest.dir}" filtering="true">
<fileset dir="${src.dir}">
<text-selector/>
</fileset>
</copy>
</target>
</project>
Output
Running Ant on the above build file produces the following output −
F:\tutorialspoint\ant>ant Buildfile: F:\tutorialspoint\ant\build.xml copy: [copy] Copying 1 file to F:\tutorialspoint\ant\build BUILD SUCCESSFUL Total time: 0 seconds
Now only .txt file is copied.