繁体   English   中英

Ant:在目录中查找文件的路径

[英]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}" />

如果没有匹配的文件,则不会回显任何内容,否则您将获得第一个匹配项的路径。

这是选择第一个匹配文件的示例。 逻辑如下:

  • 使用文件集查找所有匹配项。
  • 使用pathconvert ,将结果存储在一个属性中,用行分隔符分隔每个匹配的文件。
  • 使用 头部过滤器匹配第一个匹配文件。

该功能被封装在一个宏定义中以实现可重用性。

<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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM