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.

Prerequisite:

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

Steps:

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.

</code>

<?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"
resource="net/sf/antcontrib/antlib.xml"
classpath="../../resources/ant/ant-contrib-1.0b3.jar"/>
<target name="test">
<echo message="Folders in the directory are:"/>
<ac:foreach target="list.dirs" param="dir.name">
<path>
<dirset dir="${basedir}" includes="*"/>
</path>
</ac:foreach>
</target>

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

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

<code>

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!

Advertisements
  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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: