Apache Ant: Delete All Files in a Directory, but not in Subdirectories

When working on an Apache Ant project, you may need a task that deletes all files in a directory but not in subdirectories. This post will show you how to do this combining Delete task, Include task and Fileset type.

Let’s assume that, this is project structure:

MyProject/
    │   license
    │   readme.md
    │   release-notes.txt
    │
    ├───docs
    │       index.html
    │
    ├───images
    │       icon.jpg
    │       logo.jpg
    │
    └───src
        └───main
            └───java
                └───com
                    └───example
                            FileHelpers.java
                            Program.java

You want to delete all files (license, readme.md, release-note.txt) in MyProject directory, but not deleting files in subdirectories (docs, images, src). Here is the ant syntax how to do this:

<delete>
    <fileset dir="yourdir">
        <include name="*"/>
    </fileset>
</delete>

The above we use * wildcard that should only delete all files at the top level, not in subdirectories.

Here is how it looks in an ant build.xml file:

build.xml
<?xml version="1.0" encoding="UTF-8"?>
<project basedir="." default="main">

    <target name="main">
        <delete>
            <fileset dir="MyProject">
                <include name="*"/>
            </fileset>
        </delete>
    </target>

</project>

Let’s run ant build see how it works with the above project structure and this is the result:

MyProject/
    ├───docs
    │       index.html
    │
    ├───images
    │       icon.jpg
    │       logo.jpg
    │
    └───src
        └───main
            └───java
                └───com
                    └───example
                            FileHelpers.java
                            Program.java

As you can see the in result, the license, readme.md, and release-note.txt files are deleted completely.

That’s all. Does it work in your project? Please tell us by adding a comment in the comment form below. Thanks for reading the post.

Leave a Reply

avatar