【问题标题】:Iterating over all filenames in a directory in Ant遍历 Ant 目录中的所有文件名
【发布时间】:2014-02-19 17:48:17
【问题描述】:

我需要遍历目录中的所有文件。但我只需要每个文件的名称,而不是绝对路径。这是我使用 ant-contrib 的尝试:

<target name="store">
  <for param="file">
    <path>
      <fileset dir="." includes="*.xqm"/>
    </path>
    <sequential>
      <basename file="@{file}" property="name" />
      <echo message="@{file}, ${name}"/>
    </sequential>
  </for>              
</target>

问题是${name} 表达式只被评估一次。有没有其他方法可以解决这个问题?

【问题讨论】:

标签: ant ant-contrib


【解决方案1】:

来自ant manual basename"When this task executes, it will set the specified property to the value of the last path element of the specified file"
一旦设置的属性在 vanilla ant 中是不可变的,因此在 for 循环中使用 basename 任务时,属性“名称”保存第一个文件的值。 因此必须使用 unset="true" 的 antcontrib var 任务:

<target name="store">
 <for param="file">
  <path>
   <fileset dir="." includes="*.xqm"/>
  </path>
  <sequential>
   <var name="name" unset="true"/>
   <basename file="@{file}" property="name" />
   <echo message="@{file}, ${name}"/>
  </sequential>
 </for>              
</target>

在使用 Ant 1.8.x 或更高版本时,也可以使用 local task

<target name="store">
 <for param="file">
  <path>
   <fileset dir="." includes="*.xqm"/>
  </path>
  <sequential>
   <local name="name"/>
   <basename file="@{file}" property="name" />
   <echo message="@{file}, ${name}"/>
  </sequential>
 </for>              
</target>

最后你可以使用 Ant Flaka 代替 antcontrib :

<project xmlns:fl="antlib:it.haefelinger.flaka">
 <fl:install-property-handler />

 <fileset dir="." includes="*.xqm" id="foobar"/>

  <!-- create real file objects and access their properties -->
 <fl:for var="f" in="split('${toString:foobar}', ';')">
  <echo>
  #{  format('filename %s, last modified %tD, size %s bytes', f.tofile.toabs,f.tofile.mtime,f.tofile.size)  }
  </echo>
 </fl:for>

  <!-- simple echoing the basename -->
  <fl:for var="f" in="split('${toString:foobar}', ';')">
   <echo>#{f}</echo>
  </fl:for>  

</project>

【讨论】:

    【解决方案2】:

    如果您因为 Ant 的属性不变性标准而反对使用 var 任务,有一种方法可以利用普通属性引用 ("${}") 和迭代属性引用 (" @{}") 可以相互嵌套:

    <target name="store">
        <for param="file">
            <path>
                <fileset dir="." includes="*.xqm"/>
            </path>
            <sequential>
                <basename file="@{file}" property="@{file}" />
                <echo message="@{file}, ${@{file}}"/>
            </sequential>
        </for>              
    </target>
    

    这样,您将创建一个以每个文件名命名的新属性。

    【讨论】:

      猜你喜欢
      • 2015-03-05
      • 1970-01-01
      • 2018-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-22
      • 2012-06-15
      • 1970-01-01
      相关资源
      最近更新 更多