【问题标题】:Add JarOutputStream to ZipOutputStream将 JarOutputStream 添加到 ZipOutputStream
【发布时间】:2020-09-02 17:43:34
【问题描述】:

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

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

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

非常感谢!

【问题讨论】:

  • 你不能这样做——它不能正常工作。原因是 ZIP 和 JAR(JAR 文件本质上是另一个扩展名的 ZIP 文件)正在压缩您放入其中的文件中的原始数据。因此,您可以将 ZIP 文件的内容发送到 JarOutputStream 中,反之亦然。但是你必须先创建文件(尽管你可以在内存缓冲区中创建文件)

标签: java outputstream zipoutputstream


【解决方案1】:

我不确定“我已经生成了一个 JarOutputStream”实际上是什么意思。但是,如果您想将内容写入 JAR 文件,然后再写入 ZIP 文件,而不需要将所有内容保存在内存中,您可以通过以下方式执行此操作:

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 ...
     */
    
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-20
    • 1970-01-01
    • 2013-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多