How do I overwrite a file inside a ZIP file?

I implemented a tool to edit JAR files (which are basically ZIP files).
However, I cannot seem to update files within the ZIP file.
If I try to just write the file, I get an error

Duplicate filename: BOOT-INF/classes/application-dev.properties

I looked through the API docs:

But could not find any option to remove an existing file or override it with new data.

I believe zip format does support overwriting exisiting files, since the zip command line utility has a -u option. I think you need to use "append" mode, did you try that?

Even if possible (which it might be, since zip is random access), what should happen if the new file is bigger (or rather compresses bigger)? Should it be appended at the end and the space wasted? Should the rest of the file be rewritten? Do you eventually defragment your zip files (I don't know of any tool for this)?

It might be better to just write a new file and move it in place. That would also (on Linux/Unix at least) make the update atomic. JAR files tend to contain code and not be huge, so this should be practical. It is not like you will have tens of GB of jar files (I hope).

The ZIP format supports updating files.

If the new file is smaller, it can be replaced where it is in the file.

If it's larger, it can be appended to the end of the file. That's why in ZIP the central directory listing at the end of the file — you remove old directory listing, append new file, and append new directory listing that points to the new location.

However, this technique is designed for the old days of floppy drives where rewriting a whole file would take too long.

These days, just rebuild the ZIP file from scratch (but ideally avoiding recompression of files that didn't change).

5 Likes

Thanks all. I hacked my way around it:

2 Likes

It answers also the question - why Zip format supports multi volumes archives, where same files can occupy several volumes.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.