如何通过 Apache Ant 任务获取 ZIP 文件列表?

How to Get a List of Files in ZIP via Apache Ant Task?

我需要使用 Apache Ant 任务获取 ZIP 文件中的文件名列表,而无需先解压缩。它也应该是 OS 独立的,例如:如果 My.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 任务应该 return 上面的列表加上相对路径 + 文件名。

这里有一个有点残酷的方法,通过 script 使用 Ant 中的 javascript 语言来完成:

<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>

欢迎任何更好的解决方案。

使用 zipfileset and pathconvert, wrapped in 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。 include/exclude 如果您需要过滤 zipfile 内容 - 只需使用附加属性扩展 macrodef,zipfileset 还支持其他档案,如 jar、war、ear.