Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending files to a zip file with Java

I am currently extracting the contents of a war file and then adding some new files to the directory structure and then creating a new war file.

This is all done programatically from Java - but I am wondering if it wouldn't be more efficient to copy the war file and then just append the files - then I wouldn't have to wait so long as the war expands and then has to be compressed again.

I can't seem to find a way to do this in the documentation though or any online examples.

Anyone can give some tips or pointers?

UPDATE:

TrueZip as mentioned in one of the answers seems to be a very good java library to append to a zip file (despite other answers that say it is not possible to do this).

Anyone have experience or feedback on TrueZip or can recommend other similar libaries?

like image 764
Grouchal Avatar asked Feb 08 '10 17:02

Grouchal


People also ask

How do I combine files into a zip file?

Right-click on the file or folder. Select “Compressed (zipped) folder”. To place multiple files into a zip folder, select all of the files while hitting the Ctrl button. Then, right-click on one of the files, move your cursor over the “Send to” option and select “Compressed (zipped) folder”.

Can you append to a zip file?

There is no way one can "append" to a file in zip file using the python zipfile library.


1 Answers

In Java 7 we got Zip File System that allows adding and changing files in zip (jar, war) without manual repackaging.

We can directly write to files inside zip files as in the following example.

Map<String, String> env = new HashMap<>();  env.put("create", "true"); Path path = Paths.get("test.zip"); URI uri = URI.create("jar:" + path.toUri()); try (FileSystem fs = FileSystems.newFileSystem(uri, env)) {     Path nf = fs.getPath("new.txt");     try (Writer writer = Files.newBufferedWriter(nf, StandardCharsets.UTF_8, StandardOpenOption.CREATE)) {         writer.write("hello");     } } 
like image 54
Grzegorz Żur Avatar answered Oct 14 '22 15:10

Grzegorz Żur