Ant步步為營(5)用for和foreach的方法遍歷一個文件夾,查找到某個文件並刪除


今天有個任務是要刪除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">遍歷出來的文件名。

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM