[英]Ant: Find the path of a file in a directory
我想在目錄中找到文件的路徑(類似於 unix 'find' 命令或 'which' 命令,但我需要它獨立於平台工作)並將其保存為屬性。
試圖使用whichresource
ant 任務,但它沒有成功(我認為它只適合查看 jar 文件)。
我寧願它是純螞蟻,而不是編寫我自己的任務或使用 3rd 方擴展。
請注意,路徑中可能有多個具有該名稱的文件實例 - 我希望它只返回第一個實例(或者至少我希望能夠只選擇一個)。
有什么建議么?
一種可能性是使用第first
資源選擇器。 例如,在jars
目錄下的某處找到一個名為a.jar
的文件:
<first id="first">
<fileset dir="jars" includes="**/a.jar" />
</first>
<echo message="${toString:first}" />
如果沒有匹配的文件,則不會回顯任何內容,否則您將獲得第一個匹配項的路徑。
這是選擇第一個匹配文件的示例。 邏輯如下:
該功能被封裝在一個宏定義中以實現可重用性。
<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>
我根據馬丁克萊頓的回答創建了一個宏。
帶有宏的示例項目和從找到的文件中讀取的屬性文件
<?xml version="1.0" encoding="utf-8"?>
<project name="test properties file read" default="info">
<macrodef name="searchfile">
<attribute name="file" />
<attribute name="path" default="custom,." />
<attribute name="name" />
<sequential>
<first id="@{name}">
<multirootfileset basedirs="@{path}" includes="@{file}" erroronmissingdir="false" />
</first>
<property name="@{name}" value="${toString:@{name}}" />
</sequential>
</macrodef>
<searchfile name="custom.properties.file" file="config.properties" />
<property file="${custom.properties.file}" />
<target name="info" >
<echo>
origin ${config.origin}
</echo>
</target>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.