如何在Ant中将文件名添加到文件本身?

时间:2013-09-30 21:57:30

标签: ant

有没有办法使用Ant来为它添加每个文件的名称?所以foo.txt将来自

bar

// foo.txt
bar

这需要处理一组无法硬编码到ant脚本中的文件。

1 个答案:

答案 0 :(得分:1)

由于您希望动态确定要使用的文件,因此我建议您获取ant-contrib.jar并使用其for任务。我应该指出,这将在评论中写出文件的完整路径。

<!-- Sample usage -->
<target name="run">
  <prepend>
    <!-- Assuming you are interested in *.txt files in the resource directory -->
    <fileset dir="resource">
        <include name="**/*.txt"/>
    </fileset>
  </prepend>
</target>

<!-- Import the definitions from ant-contrib -->
<taskdef resource="net/sf/antcontrib/antlib.xml">
  <classpath>
    <pathelement location="../ant-contrib*.jar"/>
  </classpath>
</taskdef>

<!-- Create the prepend task -->
<macrodef name="prepend">
  <!-- Declare that it contains an element named "files".  Implicit means it needn't be named -->
  <element name="files" implicit="yes"/>
  <sequential>
    <!-- For loop, assigning the value of each iteration to "file" -->
    <for param="file">
      <!-- Give the for loop the files -->
      <files/>
      <sequential>
        <!-- Load the contents of the file into a property -->
        <loadfile property="@{file}-content" srcfile="@{file}"/> 
        <!-- Echo the header you want into the file -->
        <echo message="// @{file}${line.separator}" file="@{file}"/>
        <!-- Append the original contents to the file -->
        <echo message="${@{file}-content}" append="true" file="@{file}"/>
      </sequential>
    </for>
  </sequential>
</macrodef>