How do I iterate through files in an ant script?

2019-08-18 02:09发布

问题:

How would I rewrite this bash script into an ant script?

#!/bin/bash

# # # First remove files in /removals dir
cd "/removals"
for file in `ls *.jar`
do
  rm -f "/targetdir/${file}"
done

# # # Next add new files from /additions
cd "/additions"
for file in `ls *.jar`
do
  cp -f ${file} /targetdir/${file}
done

I'm having trouble conceptualizing how to iterate through the files in ant like I can in bash.

Thank you in advance.

回答1:

Ant uses a concept called filesets for acting on collections of files.

The following example demonstrates filesets being passed to the delete and copy tasks. The conditional removal logic is handled by a selector.

Example

├── build.xml
└── src
    ├── additions
    │   ├── file1.txt
    │   ├── file2.txt
    │   └── file3.txt
    └── removals
        ├── file1.txt
        └── file3.txt

Running the example

run:
   [delete] Deleting /home/mark/tmp/build/file1.txt
   [delete] Deleting /home/mark/tmp/build/file3.txt
     [copy] Copying 3 files to /home/mark/tmp/build
     [copy] Copying /home/mark/tmp/src/additions/file1.txt to /home/mark/tmp/build/file1.txt
     [copy] Copying /home/mark/tmp/src/additions/file2.txt to /home/mark/tmp/build/file2.txt
     [copy] Copying /home/mark/tmp/src/additions/file3.txt to /home/mark/tmp/build/file3.txt

build.xml

<project name="demo" default="run">

  <property name="removalsdir"  location="src/removals"/>
  <property name="additionsdir" location="src/additions"/>
  <property name="targetdir"    location="build"/>

  <target name="run">
    <mkdir dir="build"/>

    <delete verbose="true">
      <fileset dir="${targetdir}">
        <present present="both" targetdir="${removalsdir}"/>
      </fileset>
    </delete>

    <copy todir="${targetdir}" verbose="true" overwrite="true">
      <fileset dir="${additionsdir}"/>
    </copy>
  </target>

</project>