使用Apache Ant删除条件文件

时间:2018-08-29 13:44:53

标签: ant

我有一个包含文件的目录。我只需要删除其中一些条件。 例如...我的文件夹包含:

super-lib-1.0.jar
super-lib-2.0.jar
super-lib-2.1.jar
cool-lib-3.3.1.jar
cool-lib-3.3.2.jar

我只需要删除相同库的旧版本。在此示例中,我需要删除文件:super-lib-1.0.jar,super-lib-2.0.jar,cool-lib-3.3.1.jar

1 个答案:

答案 0 :(得分:0)

您可以使用ant这样的javascript来做到这一点:

<?xml version="1.0" encoding="UTF-8"?>
<project default="init" name="My Project">

    <scriptdef name="removeAllButLatest" language="javascript">
        <attribute name="dir"/>
        <![CDATA[

            dir = new java.io.File(attributes.get("dir"));
            files = dir.listFiles();
            java.util.Arrays.sort(files, new java.util.Comparator({ 
                compare: function(f1,f2) {
                    n1 = f1.getName();
                    n2 = f2.getName();
                    v1 = Number(n1.substring(n1.lastIndexOf('-')+1,n1.lastIndexOf('.')).replace(/\./g, ""));
                    v2 = Number(n2.substring(n2.lastIndexOf('-')+1,n2.lastIndexOf('.')).replace(/\./g, ""));
                    n1 = n1.substring(0, n1.lastIndexOf('-'));
                    n2 = n2.substring(0, n2.lastIndexOf('-'));
                    if (n1 < n2) {return -1;}
                    if (n1 > n2) {return 1;}
                    if (v1 < v2) {return 1;}
                    if (v1 > v2) {return -1;}
                    return 0;   
                } 
            }));

            echo = project.createTask( "echo" );

            name = "";

            for(i = 0; i < files.length; i++) {

                n = files[i].getName();
                n = n.substring(0, n.lastIndexOf('-'));

                if(n == name){
                    echo.setMessage( "deleting file: " + files[i] );
                    echo.perform();
                    files[i].delete();
                }
                else {
                    name = n;
                }
            }

      ]]>
    </scriptdef>

    <target name="init">
        <removeAllButLatest dir="/home/guest/Desktop" />
    </target>

</project>