Add JarOutputStream to ZipOutputStream

186 Views Asked by At

currently I have generated a JarOutputStream and a Directory filled with *.java files.

I want to add the final JarOutputStream to a ZipOutputStream to return a final *.zip file with the directory and the *.jar file.

Now I wanted to know, how and if I can add JarOutputStream to a ZipOutputStream.

Thanks alot!

1

There are 1 best solutions below

0
On BEST ANSWER

I'm not sure what you actually mean with "I have generated a JarOutputStream". But if you want to write content to a JAR file that is then written to a ZIP file, without the need to hold everything in memory, you could do this the following way:

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