Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to zip a folder itself using java

Suppose I have the following directory structure.

D:\reports\january\ 

Inside january there are suppose two excel files say A.xls and B.xls. There are many places where it has been written about how to zip files using java.util.zip. But I want to zip the january folder itself inside reports folder so that both january and january.zip will be present inside reports. (That means when I unzip the january.zip file I should get the january folder).

Can anyone please provide me the code to do this using java.util.zip. Please let me know whether this can be more easily done by using other libraries.

Thanks a lot...

like image 241
mukund Avatar asked Apr 12 '13 10:04

mukund


People also ask

How do I automatically zip a folder?

Right-click on the folder/folders from which the files need to be copied and choose Copywhiz–>Copy from the menu as shown below: Go to the destination folder where you wish to create the . zip file and select Copywhiz–> Paste Advanced. Under the paste options select 'Paste as compressed .

How do I zip in Java?

Steps to Compress a File in JavaPut a ZipEntry object by calling the putNextEntry(ZipEntry) method on the ZipOutputStream. The ZipEntry class represents an entry of a compressed file in the ZIP file. Read all bytes from the original file by using the Files. readAllBytes(Path) method.

How do I zip an entire folder?

Locate the file or folder that you want to zip. Press and hold (or right-click) the file or folder, select (or point to) Send to, and then select Compressed (zipped) folder. A new zipped folder with the same name is created in the same location.


1 Answers

Have you tried Zeroturnaround Zip library? It's really neat! Zip a folder is just a one liner:

ZipUtil.pack(new File("D:\\reports\\january\\"), new File("D:\\reports\\january.zip")); 

(thanks to Oleg Šelajev for the example)

like image 77
Petro Semeniuk Avatar answered Oct 07 '22 19:10

Petro Semeniuk