遍历 Ant 目录中的所有文件名 [英] Iterating over all filenames in a directory in Ant

查看:38
本文介绍了遍历 Ant 目录中的所有文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to iterate over all files in a directory. But I need just the name of each file, not absolute paths. Here's my attempt using 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} 表达式只计算一次.有没有其他方法可以解决这个问题?

The problem is that ${name} expression gets evaluated only once. Is there another approach to this problem?

推荐答案

来自 ant 手册 basename : 当这个任务执行时,它会将指定的属性设置为指定文件的最后一个路径元素的值"
属性一旦设置在 vanilla ant 中是不可变的,因此在 for 循环中使用 basename 任务时,属性name"保存第一个文件的值.因此,必须使用 unset="true" 的 antcontrib var 任务:

From 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"
Properties once set are immutable in vanilla ant, so when using basename task within for loop, the property 'name' holds the value of the first file. Therefore antcontrib var task with unset="true" has to be used :

<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 或更高版本时,也可以使用 本地任务:

Alternatively use local task, when using Ant 1.8.x or later :

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

Finally you may use Ant Flaka instead of 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>

这篇关于遍历 Ant 目录中的所有文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆