Ant: Find the path of a file in a directory

One possibility is to use the first resource selector. For example to find a file called a.jar somewhere under directory jars:

<first id="first">
    <fileset dir="jars" includes="**/a.jar" />
</first>
<echo message="${toString:first}" />

If there are no matching files nothing will be echoed, otherwise you'll get the path to the first match.


Here is an example which selects the first matching file. The logic is as follows:

  • find all matches using a fileset.
  • using pathconvert, store the result in a property, separating each matching file with line separator.
  • use a head filter to match the first matching file.

The functionality is encapsulated in a macrodef for reusability.

<project default="test">

  <target name="test">
    <find dir="test" name="*" property="match.1"/>
    <echo message="found: ${match.1}"/>
    <find dir="test" name="*.html" property="match.2"/>
    <echo message="found: ${match.2}"/>
  </target>

  <macrodef name="find">
    <attribute name="dir"/>
    <attribute name="name"/>
    <attribute name="property"/>
    <sequential>
      <pathconvert property="@{property}.matches" pathsep="${line.separator}">
        <fileset dir="@{dir}">
          <include name="@{name}"/>
        </fileset>
      </pathconvert>
      <loadresource property="@{property}">
        <string value="${@{property}.matches}"/>
        <filterchain>
          <headfilter lines="1"/>
        </filterchain>
      </loadresource>
    </sequential>
  </macrodef>

</project>

Tags:

File

Ant

Path

Find