Home > Apache Ant, General, Technology > Ant foreach Directory traversal

Ant foreach Directory traversal

This post is for parsing through directory list to list down sub-directories using ant scripting.


  1. You should’ve downloaded ant-contrib jar from http://ant-contrib.sourceforge.net/#install
  2. Add the jar into <ANT_HOME>/lib directory


You first need to refer to your contrib jar in the <project> tag of build.xml.

I created two sample directories in my C:/AntTutorial for this demo

As you can see in the screen-shot there are 2 dirs, Test 1 and Test 2. The below ant script is going to list these two directories as output.


<?xml version="1.0" encoding="UTF-8"?>
<project name="ForTest" default="build" basedir="." xmlns:ac="antlib:net.sf.antcontrib">
<taskdef uri="antlib:net.sf.antcontrib"
<target name="test">
<echo message="Folders in the directory are:"/>
<ac:foreach target="list.dirs" param="dir.name">
<dirset dir="${basedir}" includes="*"/>

<target name="list.dirs">
<echo message="${dir.name}"/>

<target name="build" depends="test" description="Test For loop"/>


Following is what you should see on executing the above build script:

In the above code if you just want to display directory names instead of absolute path, you need to use <basename tag, which is explained in another post…

That’s all for now!

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: