Question

I'm trying to read create a zip file out of a list of file paths. I wanted to have the zip file as a byte array so that i can return it as a ResponseEntity object back to the web page. the problem is when i tried FileOutputStream it works. I tried ByteArrayOutputStream the zip file is corrupted. below is the code

//FileOutputStream bos = new FileOutputStream("C:\\files\\zipfile.zip");  
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(bos);
ArrayList<String> filepaths = getAllFiles();
byte[] contents = null;

for(String path : filepaths) {
    File pdf = new File(path);

    FileInputStream fis = new FileInputStream(pdf);

    ZipEntry zipEntry = new ZipEntry(path.substring(path.lastIndexOf(File.separator)+1));
    zos.putNextEntry(zipEntry);

    byte[] buffer = new byte[1024];
    int len;
    while ((len = fis.read(buffer)) > 0) {
        zos.write(buffer,0,len);
    }

    fis.close();
    zos.closeEntry();
    zos.flush();

}
contents = new byte[bos.size()];
contents = bos.toByteArray();

zos.close();
bos.close();

for the 1st 2 line that you see above, if i use ByteArrayOutputStream, the zip file is seems corrupted. But if i use FileOutputstream i'm unable to open the zip file and it's content.

here is how I send back the zip byte array to the webpage. All these codes happen inside a spring controller method

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/zip"));
headers.setContentDispositionFormData(zipfileNm, zipfileNm);

ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(contents, headers, HttpStatus.OK);
return response;
Était-ce utile?

La solution

Have a look at Google's GUAVA library. It allow to easily copy Input to Output Streams. Also check Apache Commons Compress with special ZIP support.

However you might be able to make your life much easier...
The HTTPResponse has an OutputStream object. Instead of shuffling byte arrays through functions, you should obtain that OutputStream and hand it as a parameter to your ZIP creation function. This way you avoid requiring all the memory for the byte shuffling and the potential issues it brings with it.

Hope that helps!

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top