java.util.zip.ZipException when adding a ZipEntry to a ZipOutputStream without a ZipInputStream

StackOverflow https://stackoverflow.com/questions/21490183

  •  05-10-2022
  •  | 
  •  

Domanda

I am attempting to add a ZipEntry to a ZipOutputStream but am running into problems when trying to write the bytes.

I got the ZipEntry from a HashMap which maps file names to their ZipEntries. I chose this method because I am dealing with a large ZipInputStream and I want be able to access its contents easier than looping through the InputStream and looking for a file and getting its ZipEntry.

This causes a problem when I try to write the bytes after I added the entry. All the solutions I have found so far have needed the ZipInputStream.

Here is the code:

ZipEntry ze = entryHash.get(pathToString(path));
zos.putNextEntry(ze);
zos.write(new byte[(int)ze.getSize()]); // Problem Here
zos.closeEntry();

The error I am getting is:

java.util.zip.ZipException: invalid entry compressed size (expected 389 but got 12 bytes)
    at java.util.zip.ZipOutputStream.closeEntry(ZipOutputStream.java:248)

How can I fix this exception?

È stato utile?

Soluzione

You need to create a new ZipEntry to add to the ZipOutputStream. But your code doesn't make any sense. You're not copying the old ZipEntry to the output with this technique, you're just writing an array of zero bytes of the same size. You have to read from the old ZipEntry and write to the new output. Your technique of a map of ZipEntries isn't going to work either. A Zip file must be processed sequentially.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top