• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 105
  • Last Modified:

Return ZipOutputStream using Servlet

In my Servlet, I am creating a zip file using ZipoutputStream

public ZipOutputStream zipIt(String zipFile) {
	   byte[] buffer = new byte[1024];
	   String source = "";
	   FileOutputStream fos = null;
	   ZipOutputStream zos = null;
	   try {
	      try {
	         source = SOURCE_FOLDER.substring(SOURCE_FOLDER.lastIndexOf("\\") + 1, SOURCE_FOLDER.length());
	      }
	     catch (Exception e) {
	        source = SOURCE_FOLDER;
	        e.printStackTrace();
	     }
	     fos = new FileOutputStream(zipFile);
	     zos = new ZipOutputStream(fos);

	     System.out.println("Output to Zip : " + zipFile);
	     FileInputStream in = null;

	     for (String file : this.fileList) {
	        System.out.println("File Added : " + file);
	        ZipEntry ze = new ZipEntry(source + File.separator + file);
	        zos.putNextEntry(ze);
	        try {
	           in = new FileInputStream(SOURCE_FOLDER + File.separator + file);
	           int len;
	           while ((len = in.read(buffer)) > 0) {
	              zos.write(buffer, 0, len);
	           }
	        }
	        finally {
	           in.close();
	        }
	     }
	     zos.closeEntry();
	     System.out.println("Folder successfully compressed");
	  }

Open in new window


Once the zip is created, I would like to send it back to the client. However, to send it as a part of the response object, it needs to be a byte[]. How can I convert ZipOutputStream to byte[]?
0
ank5
Asked:
ank5
  • 2
1 Solution
 
CEHJCommented:
However, to send it as a part of the response object, it needs to be a byte[].
Hmm. I don't quite understand that. It actually needs to be written to the servlet's OutputStream, so just write it to that instead of to 'fos'

Your buffer is almost certainly too small btw
0
 
CEHJCommented:
:)
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now