3

I am using this code to download zip file containing jasper reports. How can I use less memory on my Servlet? Can I use disk space instead of memory? or is there any other way so that my server will not give me an error saying "out of memory" if many users will try to download zip file at the same time or if the zip file size is huge.

  public void zipJasper(List<JasperPrint> print) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ZipOutputStream out = new ZipOutputStream(baos);
        try {
            int k = 1;
            for (int j = 0; j <= print.size(); ++j) {
                byte[] buffer = new byte[1024];
                byte[] pdfAsBytes = JasperExportManager.exportReportToPdf(print.get(j));
                ByteArrayInputStream fis = new ByteArrayInputStream(pdfAsBytes);
                zipfile.putNextEntry(new ZipEntry(print.get(j).getName() + ".pdf"));
                int length;
                while ((length = fis.read(buffer, 0, 1024)) > 0) {
                    zipfile.write(buffer, 0, length);
                }
                //    zipfile.closeEntry();
                // close the InputStream
                fis.close();
            }
            //   zipfile.close();
        } catch (JRException ex) {
            log("An error occured", ex);
        } catch (IOException ex) {
            log("An error occured", ex);
        } finally {
            try {
                // Flush the stream
                zipfile.flush();
            } catch (Exception e) {
            }
            try {
                // Close the stream
                zipfile.close();
            } catch (Exception e) {
            }
        }
    }
Alex K
  • 22,315
  • 19
  • 108
  • 236
Khurram
  • 45
  • 4
  • 3
    It's not `ZipOutputStream` that's using memory, it's `ByteArrayOutputStream`. See the duplicate's accepted answer on how to stream data directly to the client instead of building the whole output in memory first. – Kayaman Apr 17 '17 at 19:03
  • Hi @khurram, your for loop contains an error: the condition should be: j < print.size(); – James Apr 17 '17 at 19:07

0 Answers0