【问题标题】:How to Get a List of Files in ZIP via Apache Ant Task?如何通过 Apache Ant 任务获取 ZIP 文件列表?
【发布时间】:2016-05-31 14:57:18
【问题描述】:

我需要使用 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 任务应该返回上面的列表以及相对路径 + 文件名。

【问题讨论】:

    标签: apache file ant zip


    【解决方案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>
    

    优点:您可以使用所有文件集属性,例如如果您需要过滤 zipfilecontents,请包含/排除 - 只需使用附加属性扩展 macrodef,zipfileset 还支持其他档案,如 jar、war、ear。

    【讨论】:

    【解决方案2】:

    这是通过scriptjavascript 语言在Ant 中的一种有点残忍的方式:

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

    然后可以在 &lt;target&gt; 中调用:

    <target name="testzipfile">
    
      <getfilenamesfromzipfile
          zipfile="My.zip"
          property="file.names.from.zip.file" />
    
      <echo>List of files: ${file.name.from.zip.file}.</echo>
    
    </target>
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-19
      • 1970-01-01
      • 1970-01-01
      • 2011-04-25
      • 1970-01-01
      相关资源
      最近更新 更多