title: creating zip file to byte array
body: <p>I'm trying to read create a zip file out of a list of file paths. I wanted to have the zip file as a byte array so that i can return it as a ResponseEntity object back to the web page. the problem is when i tried <em>FileOutputStream</em> it works. I tried <em>ByteArrayOutputStream</em> the zip file is corrupted. below is the code</p>
  
  <pre><code>//FileOutputStream bos = new FileOutputStream("C:\\files\\zipfile.zip");  
  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  ZipOutputStream zos = new ZipOutputStream(bos);
  ArrayList&lt;String&gt; filepaths = getAllFiles();
  byte[] contents = null;
  
  for(String path : filepaths) {
      File pdf = new File(path);
  
      FileInputStream fis = new FileInputStream(pdf);
  
      ZipEntry zipEntry = new ZipEntry(path.substring(path.lastIndexOf(File.separator)+1));
      zos.putNextEntry(zipEntry);
  
      byte[] buffer = new byte[1024];
      int len;
      while ((len = fis.read(buffer)) &gt; 0) {
          zos.write(buffer,0,len);
      }
  
      fis.close();
      zos.closeEntry();
      zos.flush();
  
  }
  contents = new byte[bos.size()];
  contents = bos.toByteArray();
  
  zos.close();
  bos.close();
  </code></pre>
  
  <p>for the 1st 2 line that you see above, if i use <em>ByteArrayOutputStream</em>, the zip file is seems corrupted. But if i use <em>FileOutputstream</em> i'm unable to open the zip file and it's content.</p>
  
  <p>here is how I send back the zip byte array to the webpage. All these codes happen inside a spring controller method</p>
  
  <pre><code>HttpHeaders headers = new HttpHeaders();
  headers.setContentType(MediaType.parseMediaType("application/zip"));
  headers.setContentDispositionFormData(zipfileNm, zipfileNm);
  
  ResponseEntity&lt;byte[]&gt; response = new ResponseEntity&lt;byte[]&gt;(contents, headers, HttpStatus.OK);
  return response;
  </code></pre>