Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renaming a File/Folder inside a Zip File in Java?

Tags:

java

rename

zip

I have a zip file containing a folder structure like

  • main-folder/
    • subFolder1/
    • subFolder2/
    • subFolder3/
      • file3.1
      • file3.2

I would like to rename folder main-folder to let's say versionXY inside that very zip file using Java.

Is there a simpler way than extracting the whole zip file and recreating a new one using the new folder names?

like image 278
Simon07 Avatar asked Dec 14 '22 04:12

Simon07


2 Answers

Zip is an archive format, so mutating generally involves rewriting the file.

Some particular features of zip also get in the way (zip is full of "features"). As well as the central directory at the end of the archive, each component file is preceded by its file name. Zip doesn't have a concept of directories - file names are just strings that happen to include "/" characters (and substrings such as "../".

So, you really need to copy the file using ZipInputStream and ZipOutputStream, renaming as you go. If you really wanted to you could rewrite the file in place doing your own buffering. The process does cause the contents to be recompressed as the standard API has no means of obtaining the data in compressed form.

Edit: @Doval points out that @megasega's answer uses Zip File System Provider in NIO, new (relative to this answer) in Java SE 7. It's performance will likely be not great, as were the archive file systems in RISC OS' GUI of thirty years ago.

like image 200
Tom Hawtin - tackline Avatar answered Dec 31 '22 02:12

Tom Hawtin - tackline


I think you'll be able to find help for this task using the Commons Compress, especially ZipArchiveEntry

like image 42
Valentin Rocher Avatar answered Dec 31 '22 00:12

Valentin Rocher