1

I have code for create zip file in servlet like this :

ByteArrayOutputStream baos =null;
baos = new ByteArrayOutputStream(); 
ZipOutputStream zos = new ZipOutputStream(baos);
for(list  of file){
    bis = new BufferedInputStream(new FileInputStream(("somefile.extn"));

    other code for add entry in zip file

    bis.close();
}
baos.flush();
zos.flush();            
zos.close(); 
baos.close();

// Return bytes

baos.toByteArray();

// Write bytes to ServletOutputStream

Is there any problem if I flush & close ByteArrayOutputStream object (baos).

Thanks for looking here :)

user207421
  • 305,947
  • 44
  • 307
  • 483
mcacorner
  • 1,304
  • 3
  • 22
  • 45
  • Possible duplicate of http://stackoverflow.com/questions/23164598/java-is-bytearrayoutputstream-safe-without-flush-and-close – OO7 Apr 29 '15 at 12:16

1 Answers1

3

It is redundant. All you need is

zos.close();

Closing the ZipOutputStream flushes and closes all the other streams it is wrapped around. See the Javadoc.

You don't even need the ByteArrayOutputStream. You should connect the ZipOutputStream directly to the servlet output stream.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • if I don't add the zos.flush() after every entry, the file download process would stuck – cozyss Nov 10 '17 at 18:07
  • @rileyss Using what code? If you're using the OP's code, that is definitely false, because of the `ByteArrayOutputStream`. If you're using other code, you're off-topic, and you need to ask another question. – user207421 Nov 10 '17 at 18:55