title: Writing zipped byte[] into file
body: <p>I am trying to write a zipfile to a <code>byte[]</code> in memory, and then write that out to disk. The resulting zipfile is corrupt.</p>
  
  <p>This works:</p>
  
  <pre><code>try (FileOutputStream fos = new FileOutputStream(Files.createTempFile("works", ".zip").toFile());
       ZipOutputStream zos = new ZipOutputStream(fos)) {
      zos.putNextEntry(new ZipEntry("test.txt"));
      zos.write("hello world".getBytes());
      zos.closeEntry();
  }
  </code></pre>
  
  <p>This is broken and creates a corrupt zip file:</p>
  
  <pre><code>try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
       ZipOutputStream zos = new ZipOutputStream(bos)) {
      zos.putNextEntry(new ZipEntry("test.txt"));
      zos.write("hello world".getBytes());
      zos.closeEntry();
  
      Files.write(Files.createTempFile("broken", ".zip"), bos.toByteArray());
  }
  </code></pre>
  
  <p>Why would the second one not work? And how can I fix it, assuming that I need to operate on a raw <code>byte[]</code> (I can't create the zip file directly into a file, since I need the <code>byte[]</code> for other purposes).</p>