您的位置:首页 > 其它

Ant步步为营(5)用for和foreach的方法遍历一个文件夹,查找到某个文件并删除

2014-05-16 15:43 816 查看
今天有个任务是要删除VM上的某个文件夹下的两个jar包。不过这个任务没有分配给我,而是分配给俺的师傅,哈哈。不过我还是自己动手写了一些脚本在本地模拟一下删除某个指定文件。

build.xml

<?xml version="1.0"?>
<project name="ForTest" default="build" >
<property file="build.properties"></property>
<!-- import the ant contrib package for using the for or foreach -->
<taskdef resource="net/sf/antcontrib/antlib.xml"/>
<!-- for achieving the traversal of folder with "foreach" tag -->
<target name="foreach">
<echo message="Folders in the directory are:"/>
<foreach target="delete_file" param="dir.name">
<path>
<!--<dirset dir="${file.dir}" includes="*"/>-->
<fileset dir="${file.dir}" includes="jar.zip" ></fileset>
</path>
</foreach>
</target>
<!-- for achieving the traversal of folder with "for" tag -->
<target name="for">
<echo message="Folders in the directory are:"/>
<for param="dir.name">
<path>
<dirset dir="${file.dir}" includes="*" />
<fileset dir="${file.dir}" includes="*" ></fileset>
</path>
<sequential>
<echo message="@{dir.name}"/>
</sequential>
</for>
</target>
<!-- print the file under the folder-->
<target name="list.dirs">
<echo message="${dir.name}"/>
</target>

<!---delete file -->
<target name="delete_file">
<delete file="${dir.name}">

</delete>
</target>

<target name="build" depends="foreach" description="Test For loop"/>
</project>

build.properties

file.dir=G:\\_files

我先解释一下这个ant的运行顺序:

<project name="ForTest" default="build" >

先由这句入口找到build这个target。

也就是

<target name="build" depends="foreach" description="Test For loop"/>

这一句依赖foreach这个target,会找到

<target name="foreach">

一句一句执行,当执行到

<foreach target="delete_file" param="dir.name">

回去找delete_file这个target,也就是

<target name="delete_file">。

注意:

> <fileset dir="${file.dir}" includes="jar.zip" ></fileset>这句是要找出想要删除的zip包,在这里也就是jar.zip

> 现在脚本中用的遍历方式是ant contrib包下的foreach的方式遍历的。for的方式没有用到但是还是写出来了。

> <taskdef resource="net/sf/antcontrib/antlib.xml"/> 加上这一句才可以用for或者是foreach的方式遍历(有多种方法引入,share一个网址:http://blog.csdn.net/sodino/article/details/16923615)

> 这里面可能还比较疑惑的就是:红色标注的地方,这个参数也就是遍历的时候用到的。

<delete file="${dir.name}">这一句中的dir.name用的是用

<foreach target="delete_file" param="dir.name">遍历出来的文件名。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐