Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Beginner
Apr 28, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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:
    //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 
catch(Exception e) 
    //handle exception 
//here is the code for the method 
public void zipDir(String dir2zip, ZipOutputStream zos) 
        //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<dirList.length; i++) 
            File f = new File(zipDir, dirList[i]); 
                //if the File object is a directory, call this 
                //function again to add its content recursively 
            String filePath = f.getPath(); 
            zipDir(filePath, zos); 
                //loop again 
            //if we reached here, the File object f was not 
            a directory 
            //create a FileInputStream on top of f 
            FileInputStream fis = new FileInputStream(f); 
            create a new zip entry 
        ZipEntry anEntry = new ZipEntry(f.getPath()); 
            //place the zip entry in the ZipOutputStream object 
            //now write the content of the file to the ZipOutputStream 
            while((bytesIn = fis.read(readBuffer)) != -1) 
                zos.write(readBuffer, 0, bytesIn); 
           //close the Stream 
catch(Exception e) 
    //handle exception 
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.
Behrouz Fallahi
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date