2016-05-31 78 views
1

我需要使用Apache Ant任務獲取ZIP文件中的文件名列表,而不先解壓縮它。這也應該是獨立於操作系統,例如:如果My.zip包含:如何通過Apache Ant任務獲取ZIP文件列表?

dir1/path/to/file1.html 
dir1/path/to/file2.jpg 
dir1/another/path/file3.txt 
dir2/some/path/to/file4.png 
dir2/file5.doc 

的Ant任務應與相對路徑+文件名返回上面的列表。

回答

1

使用zipfilesetpathconvert解決辦法,包裹在macrodef重用:

<project> 

<macrodef name="listzipcontents"> 
<attribute name="file"/> 
<attribute name="outputproperty"/> 

<sequential> 
    <zipfileset src="@{file}" id="content"/> 
    <pathconvert property="@{outputproperty}" pathsep="${line.separator}"> 
    <zipfileset refid="content"/> 
    <map from="@{file}:" to=""/> 
    </pathconvert> 
</sequential> 
</macrodef> 

    <listzipcontents file="path/to/whatever.zip|war|jar|ear" outputproperty="foobar"/> 

    <echo>$${foobar} => ${foobar}</echo> 

</project> 

優勢:你可以使用所有的文件集屬性,F.E.包括/排除,如果你需要過濾zipfilecontents - 只需擴展macrodef與其他屬性,zipfileset支持其他檔案,如罐子,戰爭,耳朵。

+0

這是一個更好的整體方法。然而,後來,我意識到我需要從壓縮文件內容中提取更多信息,即修改/時間戳的最後日期,大小,校驗和等,我覺得腳本允許簡化改進。儘管如此,我想接受你對我原來的問題的回答。 – Malvon

+0

@Malvon修改/時間戳/大小你可以採取螞蟻插件Flaka並使用zipfileset類似於我的答案的最後一個片段這裏=> http://stackoverflow.com/a/21891513,也有一個校驗和任務= > https://ant.apache.org/manual/Tasks/checksum.html;當使用Ant Flaka時,請使用這裏的最新版本=> https://github.com/greg2001/ant-flaka; – Rebse

+0

@Malvon P.S.另一個Flaka示例在這裏=> http://stackoverflow.com/a/5992436/130683,否則用腳本它會變得更復雜,請看這裏=> http://stackoverflow.com/a/14740667/130683 – Rebse

0

下面是螞蟻與javascript語言做它通過script了幾分殘酷的方式:

<scriptdef name="getfilenamesfromzipfile" language="javascript"> 
    <attribute name="zipfile" /> 
    <attribute name="property" /> 
    <![CDATA[ 

      importClass(java.util.zip.ZipInputStream); 
      importClass(java.io.FileInputStream); 
      importClass(java.util.zip.ZipEntry); 
      importClass(java.lang.System); 

      file_name = attributes.get("zipfile"); 
      property_to_set = attributes.get("property"); 

      var stream = new ZipInputStream(new FileInputStream(file_name)); 

      try { 
       var entry; 
       var list; 
       while ((entry = stream.getNextEntry()) != null) { 
        if (!entry.isDirectory()) { 
        list = list + entry.toString() + "\n"; 
        } 
       } 

       project.setNewProperty(property_to_set, list); 

      } finally { 
       stream.close(); 
      } 

    ]]> 

</scriptdef> 

然後可以在<target>被稱爲:

<target name="testzipfile"> 

    <getfilenamesfromzipfile 
     zipfile="My.zip" 
     property="file.names.from.zip.file" /> 

    <echo>List of files: ${file.name.from.zip.file}.</echo> 

</target> 

任何更好的解決方案是值得歡迎的。

相關問題