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

3

我需要使用Apache Ant任务获取ZIP文件中的文件名列表,而不需要先解压缩它。同时,它应该是操作系统无关的,例如:如果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任务应该返回上述列表,其中包含相对路径+文件名。
2个回答

2

以下是使用 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>

优点:您可以使用所有的文件集属性,例如包括/排除,如果您需要过滤zip文件内容-只需通过宏定义扩展其他属性即可。此外,zipfileset支持其他存档文件,如jar、war和ear。


这是一个更好的整体方法。然而,后来我意识到需要从zip文件内容中提取更多信息,例如修改日期/时间戳,大小,校验和等等,而我感觉编写脚本可以更容易地进行改进。尽管如此,我仍然愿意接受您对我最初问题的答案。 - Malvon
@Malvon,如果你需要修改/时间戳/大小,可以使用Ant插件Flaka,并将其与zipfileset一起使用,类似于我在这里的最后一个代码片段=> http://stackoverflow.com/a/21891513,此外,ant还有一个checksum任务=> https://ant.apache.org/manual/Tasks/checksum.html; 当使用Ant Flaka时,请使用此处的最新版本=> https://github.com/greg2001/ant-flaka; - Rebse
@Malvon P.S. 这里还有另一个 Flaka 的例子 => https://dev59.com/AFfUa4cB1Zd3GeqPERFD#5992436,否则使用脚本会更加复杂,参见这里 => https://dev59.com/sG7Xa4cB1Zd3GeqPmBpL#14740667。 - Rebse

0

这是一种有点残忍的方法,通过 javascript 语言在 Ant 中使用 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>

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接