”;
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 −
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 −
<?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:tutorialspointant>ant Buildfile: F:tutorialspointantbuild.xml copy: [copy] Copying 1 file to F:tutorialspointantbuild BUILD SUCCESSFUL Total time: 0 seconds
Now only .txt file is copied.
”;