迭代Ant中目录中的所有文件名

pra*_*pes 2 ant ant-contrib

我需要遍历目录中的所有文件.但我只需要每个文件的名称,而不是绝对路径.这是我使用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>
Run Code Online (Sandbox Code Playgroud)

问题是${name}表达式只被评估一次.还有另一种解决这个问题的方法吗?

Reb*_*bse 6

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任务时,属性'name'保存第一个文件的值.因此,必须使用带有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>
Run Code Online (Sandbox Code Playgroud)

或者,在使用Ant 1.8.x或更高版本时使用本地任务:

<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>
Run Code Online (Sandbox Code Playgroud)

最后,您可以使用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>
Run Code Online (Sandbox Code Playgroud)