Ant: find the file path in the directory

I want to find the path to the file in the directory (similar to the unix "find" command or the "which" command, but I need it to work regardless of the platform) and save it as a property.

Tried to use whichresource ant task, but that doesn't do the trick (I think this is only useful for viewing jar files).

I would prefer it to be pure ant and not write my own task or use a third-party extension.

Please note that there can be several instances of a file by this name in the path - I want it to return only the first instance (or at least I would like to select only one).

Any suggestions?

+7
source share
2 answers

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

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

If there are no corresponding files, nothing will echo, otherwise you will get the path to the first match.

+21
source

Here is an example that selects the first matching file. The logic is this:

  • find all matches using fileset .
  • using pathconvert , save the result in the property, dividing each corresponding file into a line separator.
  • use a head filter to match the first matching file.

Functionality is encapsulated in macrodef for reuse.

 <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> 
+7
source

All Articles