title: Download multiple files in parallel to a zip-file from S3 using Java
body: <p>I'd like to download multiple files from some external source like S3, create a single <code>zip</code> file containing all those files and present the user a link to download that <code>zip</code> file.</p>
  
  <p>Obviously I can process the files sequentially, reading the input stream of each one and writing it to <code>ZipOutputStream</code>.</p>
  
  <p>How can I read all the input file streams in parallel and write to a single output stream so that I can present a download link to the user without making them wait until <code>zip</code> file is fully written?</p>
  
  <p>My current code:</p>
  
  <pre><code>String realpath = getServletContext().getRealPath("/");
  response.setContentType("application/zip");
  
  response.setHeader("Content-Disposition","attachment; filename="+fi.replace('/', '-')+"_"+ff.replace('/', '-')+".zip");
  
  ServletOutputStream out = null;
  ZipOutputStream zipfile = null;
  
  try
  {
      List&lt;Object[]&gt; cfdis = /*my hibernate criteria source, your Database?*/
      out = response.getOutputStream();
      zipfile = new ZipOutputStream(out);
      ZipEntry zipentry = null;
      for(Object[] cfdi:cfdis)
      {
          zipentry = new ZipEntry(cfdi[1].toString()+".xml");
          zipfile.putNextEntry(zipentry);
          InputStream in = new FileInputStream(new File(realpath+cfdi[0].toString()));
          byte[] bytes = new byte[FILEBUFFERSIZE];
          int bytesRead;
          while ((bytesRead = in.read(bytes)) != -1)
          {
              zipfile.write(bytes, 0, bytesRead);
          }
      }
  </code></pre>