首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >向ZipOutputStream添加JarOutputStream

向ZipOutputStream添加JarOutputStream
EN

Stack Overflow用户
提问于 2020-09-03 01:43:34
回答 1查看 46关注 0票数 1

目前,我已经生成了一个目录和一个用*.java文件填充的目录。

我想将最终的JarOutputStream添加到ZipOutputStream中,以返回包含目录和*.jar文件的最终*.zip文件。

现在我想知道,如何以及是否可以向ZipOutputStream添加JarOutputStream。

非常感谢!

EN

回答 1

Stack Overflow用户

发布于 2020-09-03 03:42:38

我不确定你说的“我已经生成了一个JarOutputStream”到底是什么意思。但是,如果您想要将内容写入JAR文件,然后将其写入ZIP文件,而不需要将所有内容都保存在内存中,则可以按以下方式执行此操作:

代码语言:javascript
复制
public static class ExtZipOutputStream extends ZipOutputStream {

  public ExtZipOutputStream(OutputStream out) {
    super(out);
  }

  public JarOutputStream putJarFile(String name) throws IOException {
    ZipEntry zipEntry = new ZipEntry(name);
    putNextEntry(zipEntry);
    return new JarOutputStream(this) {

      @Override
      public void close() throws IOException {
        /* IMPORTANT: We finish writing the contents of the ZIP output stream but do 
         * NOT close the underlying ExtZipOutputStream
         */
        super.finish();
        ExtZipOutputStream.this.closeEntry();
      }
    };
  }
}

public static void main(String[] args) throws FileNotFoundException, IOException {

  try (ExtZipOutputStream zos = new ExtZipOutputStream(new FileOutputStream("target.zip"))) {
    
    try (JarOutputStream jout = zos.putJarFile("embed.jar")) {
      /*
       * Add files to embedded JAR file here ...
       */
    }
    
    /*
     * Add additional files to ZIP file here ...
     */
    
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63710948

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档