FileDocCategorySizeDatePackage
Delete.javaAPI DocApache Ant 1.7025048Wed Dec 13 06:16:18 GMT 2006org.apache.tools.ant.taskdefs

Delete

public class Delete extends MatchingTask
Deletes a file or directory, or set of files defined by a fileset. The original delete task would delete a file, or a set of files using the include/exclude syntax. The deltree task would delete a directory tree. This task combines the functionality of these two originally distinct tasks.

Currently Delete extends MatchingTask. This is intended only to provide backwards compatibility for a release. The future position is to use nested filesets exclusively.

since
Ant 1.2
ant.task
category="filesystem"

Fields Summary
private static final int
DELETE_RETRY_SLEEP_MILLIS
private static final org.apache.tools.ant.types.resources.comparators.ResourceComparator
REVERSE_FILESYSTEM
private static final org.apache.tools.ant.types.resources.selectors.ResourceSelector
EXISTS
protected File
file
protected File
dir
protected Vector
filesets
protected boolean
usedMatchingTask
protected boolean
includeEmpty
private int
verbosity
private boolean
quiet
private boolean
failonerror
private boolean
deleteOnExit
private org.apache.tools.ant.types.resources.Resources
rcs
Constructors Summary
Methods Summary
public voidadd(org.apache.tools.ant.types.selectors.FileSelector selector)
add an arbitrary selector

param
selector the selector to be added
since
Ant 1.6

        usedMatchingTask = true;
        super.add(selector);
    
public voidadd(org.apache.tools.ant.types.ResourceCollection rc)
Add an arbitrary ResourceCollection to be deleted.

param
rc the filesystem-only ResourceCollection.

        if (rc == null) {
            return;
        }
        rcs = (rcs == null) ? new Resources() : rcs;
        rcs.add(rc);
    
public voidaddAnd(org.apache.tools.ant.types.selectors.AndSelector selector)
add an "And" selector entry on the selector list

param
selector the selector to be added

        usedMatchingTask = true;
        super.addAnd(selector);
    
public voidaddContains(org.apache.tools.ant.types.selectors.ContainsSelector selector)
add a contains selector entry on the selector list

param
selector the selector to be added

        usedMatchingTask = true;
        super.addContains(selector);
    
public voidaddContainsRegexp(org.apache.tools.ant.types.selectors.ContainsRegexpSelector selector)
add a regular expression selector entry on the selector list

param
selector the selector to be added

        usedMatchingTask = true;
        super.addContainsRegexp(selector);
    
public voidaddCustom(org.apache.tools.ant.types.selectors.ExtendSelector selector)
add an extended selector entry on the selector list

param
selector the selector to be added

        usedMatchingTask = true;
        super.addCustom(selector);
    
public voidaddDate(org.apache.tools.ant.types.selectors.DateSelector selector)
add a selector date entry on the selector list

param
selector the selector to be added

        usedMatchingTask = true;
        super.addDate(selector);
    
public voidaddDepend(org.apache.tools.ant.types.selectors.DependSelector selector)
add a depends selector entry on the selector list

param
selector the selector to be added

        usedMatchingTask = true;
        super.addDepend(selector);
    
public voidaddDepth(org.apache.tools.ant.types.selectors.DepthSelector selector)
add a depth selector entry on the selector list

param
selector the selector to be added

        usedMatchingTask = true;
        super.addDepth(selector);
    
public voidaddFilename(org.apache.tools.ant.types.selectors.FilenameSelector selector)
add a selector filename entry on the selector list

param
selector the selector to be added

        usedMatchingTask = true;
        super.addFilename(selector);
    
public voidaddFileset(org.apache.tools.ant.types.FileSet set)
Adds a set of files to be deleted.

param
set the set of files to be deleted

        filesets.addElement(set);
    
public voidaddMajority(org.apache.tools.ant.types.selectors.MajoritySelector selector)
add a majority selector entry on the selector list

param
selector the selector to be added

        usedMatchingTask = true;
        super.addMajority(selector);
    
public voidaddModified(org.apache.tools.ant.types.selectors.modifiedselector.ModifiedSelector selector)
add the modified selector

param
selector the selector to add
since
ant 1.6

        usedMatchingTask = true;
        super.addModified(selector);
    
public voidaddNone(org.apache.tools.ant.types.selectors.NoneSelector selector)
add a "None" selector entry on the selector list

param
selector the selector to be added

        usedMatchingTask = true;
        super.addNone(selector);
    
public voidaddNot(org.apache.tools.ant.types.selectors.NotSelector selector)
add a "Not" selector entry on the selector list

param
selector the selector to be added

        usedMatchingTask = true;
        super.addNot(selector);
    
public voidaddOr(org.apache.tools.ant.types.selectors.OrSelector selector)
add an "Or" selector entry on the selector list

param
selector the selector to be added

        usedMatchingTask = true;
        super.addOr(selector);
    
public voidaddPresent(org.apache.tools.ant.types.selectors.PresentSelector selector)
add a present selector entry on the selector list

param
selector the selector to be added

        usedMatchingTask = true;
        super.addPresent(selector);
    
public voidaddSelector(org.apache.tools.ant.types.selectors.SelectSelector selector)
add a "Select" selector entry on the selector list

param
selector the selector to be added

        usedMatchingTask = true;
        super.addSelector(selector);
    
public voidaddSize(org.apache.tools.ant.types.selectors.SizeSelector selector)
add a selector size entry on the selector list

param
selector the selector to be added

        usedMatchingTask = true;
        super.addSize(selector);
    
public PatternSet.NameEntrycreateExclude()
add a name entry on the exclude list

return
an NameEntry object to be configured

        usedMatchingTask = true;
        return super.createExclude();
    
public PatternSet.NameEntrycreateExcludesFile()
add a name entry on the include files list

return
an NameEntry object to be configured

        usedMatchingTask = true;
        return super.createExcludesFile();
    
public PatternSet.NameEntrycreateInclude()
add a name entry on the include list

return
a NameEntry object to be configured

        usedMatchingTask = true;
        return super.createInclude();
    
public PatternSet.NameEntrycreateIncludesFile()
add a name entry on the include files list

return
an NameEntry object to be configured

        usedMatchingTask = true;
        return super.createIncludesFile();
    
public org.apache.tools.ant.types.PatternSetcreatePatternSet()
add a set of patterns

return
PatternSet object to be configured

        usedMatchingTask = true;
        return super.createPatternSet();
    
private booleandelete(java.io.File f)
Accommodate Windows bug encountered in both Sun and IBM JDKs. Others possible. If the delete does not work, call System.gc(), wait a little and try again.

        if (!f.delete()) {
            if (Os.isFamily("windows")) {
                System.gc();
            }
            try {
                Thread.sleep(DELETE_RETRY_SLEEP_MILLIS);
            } catch (InterruptedException ex) {
                // Ignore Exception
            }
            if (!f.delete()) {
                if (deleteOnExit) {
                    int level = quiet ? Project.MSG_VERBOSE : Project.MSG_INFO;
                    log("Failed to delete " + f + ", calling deleteOnExit."
                        + " This attempts to delete the file when the Ant jvm"
                        + " has exited and might not succeed.", level);
                    f.deleteOnExit();
                    return true;
                }
                return false;
            }
        }
        return true;
    
public voidexecute()
Delete the file(s).

exception
BuildException if an error occurs

        if (usedMatchingTask) {
            log("DEPRECATED - Use of the implicit FileSet is deprecated.  "
                + "Use a nested fileset element instead.", quiet ? Project.MSG_VERBOSE : verbosity);
        }

        if (file == null && dir == null && filesets.size() == 0 && rcs == null) {
            throw new BuildException("At least one of the file or dir "
                                     + "attributes, or a nested resource collection, "
                                     + "must be set.");
        }

        if (quiet && failonerror) {
            throw new BuildException("quiet and failonerror cannot both be "
                                     + "set to true", getLocation());
        }

        // delete the single file
        if (file != null) {
            if (file.exists()) {
                if (file.isDirectory()) {
                    log("Directory " + file.getAbsolutePath()
                        + " cannot be removed using the file attribute.  "
                        + "Use dir instead.", quiet ? Project.MSG_VERBOSE : verbosity);
                } else {
                    log("Deleting: " + file.getAbsolutePath());

                    if (!delete(file)) {
                        handle("Unable to delete file " + file.getAbsolutePath());
                    }
                }
            } else {
                log("Could not find file " + file.getAbsolutePath()
                    + " to delete.", quiet ? Project.MSG_VERBOSE : verbosity);
            }
        }

        // delete the directory
        if (dir != null && dir.exists() && dir.isDirectory()
            && !usedMatchingTask) {
            /*
               If verbosity is MSG_VERBOSE, that mean we are doing
               regular logging (backwards as that sounds).  In that
               case, we want to print one message about deleting the
               top of the directory tree.  Otherwise, the removeDir
               method will handle messages for _all_ directories.
             */
            if (verbosity == Project.MSG_VERBOSE) {
                log("Deleting directory " + dir.getAbsolutePath());
            }
            removeDir(dir);
        }
        Resources resourcesToDelete = new Resources();
        resourcesToDelete.setProject(getProject());
        Resources filesetDirs = new Resources();
        filesetDirs.setProject(getProject());
        FileSet implicit = null;
        if (usedMatchingTask && dir != null && dir.isDirectory()) {
            //add the files from the default fileset:
            implicit = getImplicitFileSet();
            implicit.setProject(getProject());
            filesets.add(implicit);
        }

        for (int i = 0, size = filesets.size(); i < size; i++) {
            FileSet fs = (FileSet) filesets.get(i);
            if (fs.getProject() == null) {
                log("Deleting fileset with no project specified;"
                    + " assuming executing project", Project.MSG_VERBOSE);
                fs = (FileSet) fs.clone();
                fs.setProject(getProject());
            }
            if (!fs.getDir().isDirectory()) {
                handle("Directory does not exist:" + fs.getDir());
            } else {
                resourcesToDelete.add(fs);
                if (includeEmpty) {
                    filesetDirs.add(new ReverseDirs(fs.getDir(), fs
                            .getDirectoryScanner().getIncludedDirectories()));
                }
            }
        }
        resourcesToDelete.add(filesetDirs);
        if (rcs != null) {
            // sort first to files, then dirs
            Restrict exists = new Restrict();
            exists.add(EXISTS);
            exists.add(rcs);
            Sort s = new Sort();
            s.add(REVERSE_FILESYSTEM);
            s.add(exists);
            resourcesToDelete.add(s);
        }
        try {
            if (resourcesToDelete.isFilesystemOnly()) {
                for (Iterator iter = resourcesToDelete.iterator(); iter.hasNext();) {
                    FileResource r = (FileResource) iter.next();
                    // nonexistent resources could only occur if we already
                    // deleted something from a fileset:
                    if (!r.isExists()) {
                        continue;
                    }
                    if (!(r.isDirectory()) || r.getFile().list().length == 0) {
                        log("Deleting " + r, verbosity);
                        if (!delete(r.getFile()) && failonerror) {
                            handle("Unable to delete "
                                + (r.isDirectory() ? "directory " : "file ") + r);
                        }
                    }
                }
            } else {
                 handle(getTaskName() + " handles only filesystem resources");
            }
        } catch (Exception e) {
            handle(e);
        } finally {
            if (implicit != null) {
                filesets.remove(implicit);
            }
        }
    
private voidhandle(java.lang.String msg)

        handle(new BuildException(msg));
    
private voidhandle(java.lang.Exception e)

        if (failonerror) {
            throw (e instanceof BuildException)
                ? (BuildException) e : new BuildException(e);
        }
        log(e, quiet ? Project.MSG_VERBOSE : verbosity);
    
protected voidremoveDir(java.io.File d)
Delete a directory

param
d the directory to delete

        String[] list = d.list();
        if (list == null) {
            list = new String[0];
        }
        for (int i = 0; i < list.length; i++) {
            String s = list[i];
            File f = new File(d, s);
            if (f.isDirectory()) {
                removeDir(f);
            } else {
                log("Deleting " + f.getAbsolutePath(), quiet ? Project.MSG_VERBOSE : verbosity);
                if (!delete(f)) {
                    handle("Unable to delete file " + f.getAbsolutePath());
                }
            }
        }
        log("Deleting directory " + d.getAbsolutePath(), verbosity);
        if (!delete(d)) {
            handle("Unable to delete directory " + dir.getAbsolutePath());
        }
    
protected voidremoveFiles(java.io.File d, java.lang.String[] files, java.lang.String[] dirs)
remove an array of files in a directory, and a list of subdirectories which will only be deleted if 'includeEmpty' is true

param
d directory to work from
param
files array of files to delete; can be of zero length
param
dirs array of directories to delete; can of zero length

        if (files.length > 0) {
            log("Deleting " + files.length + " files from "
                + d.getAbsolutePath(), quiet ? Project.MSG_VERBOSE : verbosity);
            for (int j = 0; j < files.length; j++) {
                File f = new File(d, files[j]);
                log("Deleting " + f.getAbsolutePath(),
                        quiet ? Project.MSG_VERBOSE : verbosity);
                if (!delete(f)) {
                    handle("Unable to delete file " + f.getAbsolutePath());
                }
            }
        }

        if (dirs.length > 0 && includeEmpty) {
            int dirCount = 0;
            for (int j = dirs.length - 1; j >= 0; j--) {
                File currDir = new File(d, dirs[j]);
                String[] dirFiles = currDir.list();
                if (dirFiles == null || dirFiles.length == 0) {
                    log("Deleting " + currDir.getAbsolutePath(),
                            quiet ? Project.MSG_VERBOSE : verbosity);
                    if (!delete(currDir)) {
                        handle("Unable to delete directory "
                                + currDir.getAbsolutePath());
                    } else {
                        dirCount++;
                    }
                }
            }

            if (dirCount > 0) {
                log("Deleted "
                     + dirCount
                     + " director" + (dirCount == 1 ? "y" : "ies")
                     + " form " + d.getAbsolutePath(),
                     quiet ? Project.MSG_VERBOSE : verbosity);
            }
        }
    
public voidsetCaseSensitive(boolean isCaseSensitive)
Sets case sensitivity of the file system

param
isCaseSensitive "true"|"on"|"yes" if file system is case sensitive, "false"|"off"|"no" when not.

        usedMatchingTask = true;
        super.setCaseSensitive(isCaseSensitive);
    
public voidsetDefaultexcludes(boolean useDefaultExcludes)
Sets whether default exclusions should be used or not.

param
useDefaultExcludes "true"|"on"|"yes" when default exclusions should be used, "false"|"off"|"no" when they shouldn't be used.

        usedMatchingTask = true;
        super.setDefaultexcludes(useDefaultExcludes);
    
public voidsetDeleteOnExit(boolean deleteOnExit)
If true, on failure to delete, note the error and set the deleteonexit flag, and continue

param
deleteOnExit true or false

         this.deleteOnExit = deleteOnExit;
     
public voidsetDir(java.io.File dir)
Set the directory from which files are to be deleted

param
dir the directory path.

        this.dir = dir;
        getImplicitFileSet().setDir(dir);
    
public voidsetExcludes(java.lang.String excludes)
Sets the set of exclude patterns. Patterns may be separated by a comma or a space.

param
excludes the string containing the exclude patterns

        usedMatchingTask = true;
        super.setExcludes(excludes);
    
public voidsetExcludesfile(java.io.File excludesfile)
Sets the name of the file containing the includes patterns.

param
excludesfile A string containing the filename to fetch the include patterns from.

        usedMatchingTask = true;
        super.setExcludesfile(excludesfile);
    
public voidsetFailOnError(boolean failonerror)
If false, note errors but continue.

param
failonerror true or false

         this.failonerror = failonerror;
     
public voidsetFile(java.io.File file)
Set the name of a single file to be removed.

param
file the file to be deleted

    // CheckStyle:VisibilityModifier ON

                          
        
        this.file = file;
    
public voidsetFollowSymlinks(boolean followSymlinks)
Sets whether or not symbolic links should be followed.

param
followSymlinks whether or not symbolic links should be followed

        usedMatchingTask = true;
        super.setFollowSymlinks(followSymlinks);
    
public voidsetIncludeEmptyDirs(boolean includeEmpty)
If true, delete empty directories.

param
includeEmpty if true delete empty directories (only for filesets). Default is false.

        this.includeEmpty = includeEmpty;
    
public voidsetIncludes(java.lang.String includes)
Sets the set of include patterns. Patterns may be separated by a comma or a space.

param
includes the string containing the include patterns

        usedMatchingTask = true;
        super.setIncludes(includes);
    
public voidsetIncludesfile(java.io.File includesfile)
Sets the name of the file containing the includes patterns.

param
includesfile A string containing the filename to fetch the include patterns from.

        usedMatchingTask = true;
        super.setIncludesfile(includesfile);
    
public voidsetQuiet(boolean quiet)
If true and the file does not exist, do not display a diagnostic message or modify the exit status to reflect an error. This means that if a file or directory cannot be deleted, then no error is reported. This setting emulates the -f option to the Unix "rm" command. Default is false meaning things are "noisy"

param
quiet "true" or "on"

        this.quiet = quiet;
        if (quiet) {
            this.failonerror = false;
        }
    
public voidsetVerbose(boolean verbose)
If true, list all names of deleted files.

param
verbose "true" or "on"

        if (verbose) {
            this.verbosity = Project.MSG_INFO;
        } else {
            this.verbosity = Project.MSG_VERBOSE;
        }