Marco said:
You could copy from an existing Zip archive into a new one, replace
and add as you like, then delete the old archive and rename the new
one. That's what "real" Zip tools do as well, in-place editing does
not work well with the Zip format.
If I understand the ZIP file format correctly, you can have the central
directory at the end of the file. This should make it possible to have
an efficient "add to archive" function if you have random file access.
An algorithm could roughly look like it follows:
open zip file (maybe use memory-mapped io)
locate central directory
read central directory data and save to memory
determine start position for the new entry in the file (if the
central directory was at the end, this will be the
former beginning of the central directory)
write entry to the file
determine new position of central directory
adjust directory data (AFAIR it contains relative positions)
add directory entry for the new file
append central directory to the zip file
adjust (if any) other header information to point to new
central directory (I don't remember if there is
something like this in the zip format)
Removing an entry would be a little bit more work. You would have to
copy the data following the to-be-removed entry over the entry's data,
and you would then have to adjust the central directory.
Replacing an entry would depend on the size of the new entry.
However, since you would do all this in-place, it would be a good idea
to have a backup of the zip file. But if you have to create a backup,
you could also write the new file from scratch, instead of creating the
backup.
However, "real" Zip tools probably have a more efficient way of
copying data - if you copy archive entry data from the old to the new
archive with java.util.zip, it most likely is decompressed and then
compressed again, which is wasteful.
Yes, the Java API unfortunately lacks access to the raw data of a zip
entry. You just get an input stream which delivers the decompressed
data. ZipFile has the necessary methods and a support class, but they
are private :-(
/Thomas