title: how to flush the ZipOutputStream periodically in java
body: <p>I am trying to archive list of files in zip format and then downloading it for the user on the fly...</p>
  
  <p>I am facing out of memory issue when downloading a zip of 1gb size </p>
  
  <p>Please help me how i can resolve this without increasing jvm heap size. i would like to flush the stream periodically..</p>
  
  <p>I AM TRYING TO FLUSH PERIODICALLY BUT THIS IS NOT WORKING FOR ME.</p>
  
  <p>Please find my code attached below:</p>
  
  <pre><code>try{
  ServletOutputStream out = response.getOutputStream();
          ZipOutputStream zip = new ZipOutputStream(out);
  
          response.setContentType("application/octet-stream");
          response.addHeader("Content-Disposition",
                  "attachment; filename=\"ResultFiles.zip\"");
                    //adding multiple files to zip
          ZipUtility.addFileToZip("c:\\a", "print1.txt", zip);
  ZipUtility.addFileToZip("c:\\a", "print2.txt", zip);
  ZipUtility.addFileToZip("c:\\a", "print3.txt", zip);
  ZipUtility.addFileToZip("c:\\a", "print4.txt", zip);
  
  zip.flush();        
  zip.close();
  out.close();
  } catch (ZipException ex) {
              System.out.println("zip exception");             
          } catch (Exception ex) {
              System.out.println("exception");
              ex.printStackTrace();   
  }
  </code></pre>
  
  <hr>
  
  <pre><code>public class ZipUtility {
  
      static public void addFileToZip(String path, String srcFile,
              ZipOutputStream zip) throws Exception {
  
          File file = new File(path + "\\" + srcFile);
          boolean exists = file.exists();
          if (exists) {
  
              long fileSize = file.length();
              int buffersize = (int) fileSize;
              byte[] buf = new byte[buffersize];
  
              int len;
              FileInputStream fin = new FileInputStream(path + "\\" + srcFile);
              zip.putNextEntry(new ZipEntry(srcFile));
              int bytesread = 0, bytesBuffered = 0;
              while ((bytesread = fin.read(buf)) &gt; -1) {
                  zip.write(buf, 0, bytesread);
                  bytesBuffered += bytesread;
                  if (bytesBuffered &gt; 1024 * 1024) { //flush after 1mb
                      bytesBuffered = 0;
                      zip.flush();
  
                  }
              }
              zip.closeEntry();
              zip.flush();
              fin.close();
          }
  
      }
  }
  
  }
  </code></pre>