How to check if directory exists before deleting it, using ANT?

with vanilla ant you would use something like =

 <target name="check">
  <condition property="deldir">
    <available file="${somedir}" type="dir"/>
  </condition>
 </target>

 <target name="deldir" depends="check" if="deldir">
 <delete dir="${somedir}"/>
    <!-- .. -->
 </target>

else see = Ant check existence for a set of files
for a similar question


For this specific case, I'm not going to answer the question "how to find if a directory exists", because that's already been answered, but I'm just going to point out that in your clean task you can use failonerror="false" to keep the ant task from exiting. This should be suitable in a clean task because if there's nothing to clean, it should not be a problem.

    <target name="clean" description="clean">
        <delete dir="${build}" failonerror="false"/>
        ....
        <delete dir="${report}" failonerror="false"/>
    </target>

This is useful if you don't want to install ant-contrib or can't for some reason.


Nice and clean solution below: Using ant-contribs.jar

When using this solution, be sure to put the following line on top

<!-- For <if> statements -->
<taskdef resource="net/sf/antcontrib/antlib.xml" />


<!-- Remove distribution directories and their content for a clean build -->
    <target name="clean" description="clean">

        <if>
            <available file="${build}" type="dir" />
            <then>
                <delete dir="${build}" />
            </then>
        </if>
    </target>

Tags:

Ant

Build