Java Code For Getting A List of Files From A FileSet

Erik Hatcher

Directly from Java Development with Ant:

19.5 OPERATING ON A FILESET Ant's datatypes make writing tasks that deal with many of the typical Java build domain objects such as paths and filesets much simpler. If you are writing a task to process files in a single directory tree and would like your task to act as an implicit fileset, the base class org.apache.tools.ant.taskdefs.MatchingTask can save a lot of work. Listing 19.4 shows a task to process a set of files.

package org.example.antbook.tasks;

import java.io.File;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.MatchingTask;

public class FileProcTask extends MatchingTask {
    private File dir;

    public void setDir (File dir) {
        this.dir = dir;

    public void execute() throws BuildException {
        if (dir == null) {
            throw new BuildException("dir must be specified");
        log("dir = " + dir, Project.MSG_DEBUG);

        DirectoryScanner ds = getDirectoryScanner(dir);
        String[] files = ds.getIncludedFiles();
        for (int i = 0; i < files.length; i++) {
            log("file: " + files[i]);
        dir = null;
Listing 19.4 A task to act upon an implicit fileset
Using MatchingTask provides some nice freebies that mirror the <fileset> datatype:
  • includes/excludes attributes
  • defaultexcludes attribute
  • <include>/<exclude> / <includesfile> / <excludesfile> elements • <patternset> element
The one piece that you must provide in your own code is the directory to use with the implicit fileset. In our example we implemented a setDir method and required that a dir attribute be specified by throwing a BuildException in execute if it was not specified. The MatchingTask base class provides a getDirectoryScanner( File baseDir) method to get a DirectoryScanner instance, taking into account all the specified inclusion and exclusion rules. Although many Ant tasks are derived from MatchingTask, the current trend is away from this task; explicit filesets have proven to be more flexible. If you are writing your own task, the ease of using MatchingTask as a base class still makes it appealing. Tasks that extend from MatchingTask should only deal with a single implicit fileset. Tasks that need to support multiple nested filesets should extend from Task instead.
About | Sitemap | Contact