Compressing binary data in Java
I tried to compress a set of binary data (the result set returned from the database) into a file It can be downloaded through a web application The following code is used to compress the result set and write the zip file to httpservletresponse
String outFilename = "outfile.zip"; response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition","attachment; filename= " + outFilename); OutputStream os = response.getOutputStream(); ZipOutputStream out = new ZipOutputStream(os); for (int i = 0; i < cardFileList.size(); i++) { CardFile cardFile = cardFileList.get(i); out.putNextEntry(new ZipEntry(cardFile.getBinaryFileName())); out.write(cardFile.getBinaryFile(),cardFile.getBinaryFile().length); out.closeEntry(); } // Complete the ZIP file out.flush(); out.close(); os.close();
The problem is that when using WinRAR to extract the downloaded zip file, I receive the following error:
Can anyone point out where I made a mistake? Any help will be greatly appreciated
[editor] I tried response setContentType(“application / zip”); But the results are the same
Solution
The following codes apply to me:
FileOutputStream os = new FileOutputStream("out.zip"); ZipOutputStream zos = new ZipOutputStream(os); try { for (int i = 1; i <= 5; i++) { ZipEntry curEntry = new ZipEntry("file" + i + ".txt"); zos.putNextEntry(curEntry); zos.write(("Good morning " + i).getBytes("UTF-8")); } } finally { zos.close(); }
The zip file generated with this code is opened in 7 - Zip without any problem
>Check that the response from the servlet is not actually a 404 or 500 error page Select a small response and open it using a hex editor or even a text editor Zip files start with "PK" magic numbers and should be visible even in a text editor. > Try saving to a file instead of a beginner's servlet output stream to see if you can make a difference. > Is there a filter to modify the output / destroy zip of the servlet?