| Author |
OutOfMemoryError when downloading files
|
Chris Wang
Ranch Hand
Joined: Jan 13, 2004
Posts: 34
|
|
Hi All, I am creating a web application in which users can download multiple audio files from database as a zip file. Here is the code segment: try{ String fileName = "TestCase_Results_"+planId; ByteArrayOutputStream bout=new ByteArrayOutputStream(); ZipOutputStream zout=new ZipOutputStream(bout); ServletOutputStream out = httpServletResponse.getOutputStream(); zout.putNextEntry(new ZipEntry(fileName+".xml")); zout.write(exportedTestCaseResults2XML.getBytes()); zout.closeEntry(); zout.putNextEntry(new ZipEntry(fileName+".html")); zout.write(exportedTestCaseResults2HTML.getBytes()); zout.closeEntry(); List<String> recordings = documentAndRecordings.getRecordings(); for(String recording : recordings) { if(recording != null && !recording.equals("")) { final Blob blob = AIMT_DB.getRecoridngBlob(recording); try { Long.parseLong(recording);//make sure the name is a number. zout.putNextEntry(new ZipEntry(recording+".wav")); zout.write(blob.getBytes(1, (int)blob.length())); zout.closeEntry(); } catch(Exception e) { logger.error(e.getMessage()); } } } zout.finish(); httpServletResponse.setContentType("application/zip"); httpServletResponse.setHeader("Content-Disposition","attachment; filename="+fileName+".zip;"); httpServletResponse.setContentLength(bout.size()); out.write(bout.toByteArray()); out.flush(); When I was testing this download feature, if the audio files are more or the size of a individual audio is bigger, I got an exception: java.lang.OutOfMemoryError: Java heap space How to fix this? Any help is greatly appreciated! Chris
|
 |
Adeel Ansari
Ranch Hand
Joined: Aug 15, 2004
Posts: 2874
|
|
How about writing the zip file to the disk temporarily and then throw that to the user. Or you can avoid this by increasing your heap space. I would prefer the former one.
|
 |
Chris Wang
Ranch Hand
Joined: Jan 13, 2004
Posts: 34
|
|
Hi Adeel, Thank you for your reply. Actually I was improperly using a memory stream -- ByteArrayOutputStream as the actual stream for the ZipOutputStream, thus all the files will write to memory, for sure causing out-of-memory exception is just a matter of time. To fix this I change the code as follows: String fileName = "TestCase_Results_"+planId; httpServletResponse.setContentType("application/zip"); httpServletResponse.setHeader("Content-Disposition","attachment; filename=TestCase_"+planId+"_Results.zip;"); ServletOutputStream out = httpServletResponse.getOutputStream(); ZipOutputStream zout=new ZipOutputStream(out);//use ServletOutputStream as actual OutputStream for zip file instead of ByteArrayOutputStream. ... Cheers Chris
|
 |
Adeel Ansari
Ranch Hand
Joined: Aug 15, 2004
Posts: 2874
|
|
Right. I missed the point. Thanks, Chris, for sharing the fix. [ January 30, 2007: Message edited by: Adeel Ansari ]
|
 |
 |
|
|
subject: OutOfMemoryError when downloading files
|
|
|