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

查看:594
本文介绍了遍历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?

推荐答案

来自辅助手册基本名称执行此任务时,会将指定的属性设置为指定的最后一个路径元素的值file

属性一旦设置就无法更改,因此在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>

或者使用本地任务

<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天全站免登陆