简体   繁体   中英

Error Creating zip file In Memory using Java

Here is the code that I'm using to create a zip file:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream out = new ZipOutputStream(baos);
try {
    for(int i=0; i<docId.length; i++){
        BoxDotComDocumentManager docman = new BoxDotComDocumentManager();
        Document d = docman.get(docId[i]);
        ZipEntry entry = new ZipEntry(d.getFileName());
        entry.setSize(d.getFileBytes().length);
        out.putNextEntry(entry);
        out.write(d.getFileBytes());
        resp.setContentType("application/zip");
        resp.setHeader("Content-Disposition", "attachment; filename="+ "zipdemo.zip"); 
        out.closeEntry();
 }
 } catch (Exception e) {
      System.out.println("E = " + e);
 }
 try {
       resp.getOutputStream().write(baos.toByteArray());
   resp.flushBuffer();
} catch (IOException e) {
   e.printStackTrace();
    }
 finally {
baos.close();
out.close();
 }

the zip file is being returned to the browser to be downloaded but when I attempt to download the file I'm receiving an error stating that the file cannot be downloaded because the zip file is invalid.

Document is an object which contains all of the information about a file including the actual file.

Any ideas as to what I'm doing wrong? I've tried a lot of permutations of this and none of them seem to work. Thank you in advance.

Keith

Try using the out.write method with 3 arguments.

Replace: out.write(d.getFileBytes());

With: out.write(d.getFileBytes(),0,d.getFileBytes().length);


Note: According to the java doc the write method with one parameter doesn't get read.

Writes b.length bytes to this output stream.

The write method of FilterOutputStream calls its write method of three arguments with the arguments b, 0, and b.length.

Note that this method does not call the one-argument write method of its underlying stream with the single argument b.

Making this change in my own code fixed my problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM