devxlogo

Zip a Directory In Java

Zip a Directory In Java

Through its java.util.zip package, Java provides you with an easy mechanism to compress/decompress files. Here is a method called zipDir, that shows how to recursively zip a directory structure.

Note that the following method does not add an empty directory to the produced ZIP file.

//the method accepts a String for the directory that should be zipped, and a ZipOutputStream to write the zipped data to.

So the code to invoke the method might be:

 try {     //create a ZipOutputStream to zip the data to     ZipOutputStream zos = new            ZipOutputStream(new FileOutputStream(".\curDir.zip"));     //assuming that there is a directory named inFolder (If there     //isn't create one) in the same directory as the one the code     runs from,     //call the zipDir method     zipDir(".\inFolder", zos);     //close the stream     zos.close(); } catch(Exception e) {     //handle exception } //here is the code for the method public void zipDir(String dir2zip, ZipOutputStream zos) {     try    {         //create a new File object based on the directory we         have to zip File               zipDir = new File(dir2zip);         //get a listing of the directory content         String[] dirList = zipDir.list();         byte[] readBuffer = new byte[2156];         int bytesIn = 0;         //loop through dirList, and zip the files         for(int i=0; i

Now, you should have a curDir.zip in the application's directory. If you view it with a ZIP utility, you'll see that it contains the contents of the directory inFolder.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist