2

I have to create ZIP archive in memory But now, I need it to be saved in a real .zip file in a disk. How to do it? Pseudocode:

public byte[] crtZipByteArray(ByteArrayInputStream data,ZipEntry entry) throws IOException{
     ByteArrayOutputStream zipout = new ByteArrayOutputStream(); 
    ZipOutputStream zos = new ZipOutputStream(zipout);
    byte[] buffer = new byte[1024];
    int len;
    zos.putNextEntry(entry);
    while ((len = data.read(buffer)) > 0) {
        zos.write(buffer, 0, len);
    }
    zos.closeEntry();

    zos.close();
    data.close();
    return zipout.toByteArray();
}
Danielson
  • 2,605
  • 2
  • 28
  • 51
Serg88
  • 41
  • 2
  • 3

1 Answers1

0

Replace ByteArrayOutputStream zipout with FileOutputStream zipout.

If you sill need to return byte array as method result use apache commons TeeOutputStream to duplicate output for two streams.

public byte[] crtZipByteArray(ByteArrayInputStream data,ZipEntry entry) throws IOException{
        ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream(); 
        OutputStream fileOut = new FileOutputStream("filename.zip");
        OutputStream teeOut = new TeeOutputStream(byteArrayOut, fileOut);
        ZipOutputStream zos = new ZipOutputStream(teeOut);
.....
}