Tutorial

Java Zip File Folder Example

Published on August 3, 2022
Default avatar

By Pankaj

Java Zip File Folder Example

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Today we will look into java zip file example. We will also compress a folder and create zip file using java program.

Java ZIP

java.util.zip.ZipOutputStream can be used to compress a file into ZIP format. Since a zip file can contain multiple entries, ZipOutputStream uses java.util.zip.ZipEntry to represent a zip file entry.

Java ZIP File

java zip file, java zip folder, java zip example Creating a zip archive for a single file is very easy, we need to create a ZipOutputStream object from the FileOutputStream object of destination file. Then we add a new ZipEntry to the ZipOutputStream and use FileInputStream to read the source file to ZipOutputStream object. Once we are done writing, we need to close ZipEntry and release all the resources.

Java Zip Folder

Zipping a directory is little tricky, first we need to get the files list as absolute path. Then process each one of them separately. We need to add a ZipEntry for each file and use FileInputStream to read the content of the source file to the ZipEntry corresponding to that file.

Java Zip Example

Here is the java program showing how to zip a single file or zip a folder in java.

package com.journaldev.files;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipFiles {
    
    List<String> filesListInDir = new ArrayList<String>();

    public static void main(String[] args) {
        File file = new File("/Users/pankaj/sitemap.xml");
        String zipFileName = "/Users/pankaj/sitemap.zip";
        
        File dir = new File("/Users/pankaj/tmp");
        String zipDirName = "/Users/pankaj/tmp.zip";
        
        zipSingleFile(file, zipFileName);
        
        ZipFiles zipFiles = new ZipFiles();
        zipFiles.zipDirectory(dir, zipDirName);
    }

    /**
     * This method zips the directory
     * @param dir
     * @param zipDirName
     */
    private void zipDirectory(File dir, String zipDirName) {
        try {
            populateFilesList(dir);
            //now zip files one by one
            //create ZipOutputStream to write to the zip file
            FileOutputStream fos = new FileOutputStream(zipDirName);
            ZipOutputStream zos = new ZipOutputStream(fos);
            for(String filePath : filesListInDir){
                System.out.println("Zipping "+filePath);
                //for ZipEntry we need to keep only relative file path, so we used substring on absolute path
                ZipEntry ze = new ZipEntry(filePath.substring(dir.getAbsolutePath().length()+1, filePath.length()));
                zos.putNextEntry(ze);
                //read the file and write to ZipOutputStream
                FileInputStream fis = new FileInputStream(filePath);
                byte[] buffer = new byte[1024];
                int len;
                while ((len = fis.read(buffer)) > 0) {
                    zos.write(buffer, 0, len);
                }
                zos.closeEntry();
                fis.close();
            }
            zos.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * This method populates all the files in a directory to a List
     * @param dir
     * @throws IOException
     */
    private void populateFilesList(File dir) throws IOException {
        File[] files = dir.listFiles();
        for(File file : files){
            if(file.isFile()) filesListInDir.add(file.getAbsolutePath());
            else populateFilesList(file);
        }
    }

    /**
     * This method compresses the single file to zip format
     * @param file
     * @param zipFileName
     */
    private static void zipSingleFile(File file, String zipFileName) {
        try {
            //create ZipOutputStream to write to the zip file
            FileOutputStream fos = new FileOutputStream(zipFileName);
            ZipOutputStream zos = new ZipOutputStream(fos);
            //add a new Zip Entry to the ZipOutputStream
            ZipEntry ze = new ZipEntry(file.getName());
            zos.putNextEntry(ze);
            //read the file and write to ZipOutputStream
            FileInputStream fis = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }
            
            //Close the zip entry to write to zip file
            zos.closeEntry();
            //Close resources
            zos.close();
            fis.close();
            fos.close();
            System.out.println(file.getCanonicalPath()+" is zipped to "+zipFileName);
            
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

Output of the above java zip example program is:

/Users/pankaj/sitemap.xml is zipped to /Users/pankaj/sitemap.zip
Zipping /Users/pankaj/tmp/.DS_Store
Zipping /Users/pankaj/tmp/data/data.dat
Zipping /Users/pankaj/tmp/data/data.xml
Zipping /Users/pankaj/tmp/data/xmls/project.xml
Zipping /Users/pankaj/tmp/data/xmls/web.xml
Zipping /Users/pankaj/tmp/data.Xml
Zipping /Users/pankaj/tmp/DB.xml
Zipping /Users/pankaj/tmp/item.XML
Zipping /Users/pankaj/tmp/item.xsd
Zipping /Users/pankaj/tmp/ms/data.txt
Zipping /Users/pankaj/tmp/ms/project.doc

Notice that while logging files to zip in directory, I am printing absolute path. But while adding zip entry, I am using relative path from the directory so that when we unzip it, it will create the same directory structure. That’s all for Java zip example.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Pankaj

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
February 10, 2021

I would like to know, how to zip individual files that all end in the extension of .txt and then have them preserve their name.

- don-pierre

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    October 22, 2019

    Hi, Are there anything which can allow to compress a file in different modes like fast compression or full compression. Thanks, Nitish Kashyap

    - Nitish Kashyap

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      May 20, 2019

      how to preserve file permissions?

      - Sahil Doshi

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        December 14, 2015

        Thank You …

        - Vaibhav G

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          August 8, 2014

          Hiii… can you give me a source code of unzip a file with its hirarchy. suppose i have a zip file “DICOM.zip” and it contains a directory called “root”. now again root contains “subroot”. now “subroot” contains three folder “A”,“B”,“C”. and "A"contains some files like a1.img,a2.img,a3.img etc. and “B” and “C” also contains same type of files. So my quation is that, i want such a java program to unzip my “DICOM.zip” so that it can extract the all file with same hirarchy as source hirarchy of the directory. Thanks in advance.

          - sunil mali

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            May 14, 2014

            ZipFiles zipFiles = new ZipFiles(); how i can handle this error

            - hardeep

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              April 29, 2014

              Hi, how can i save many folders into the zip file?

              - Airam

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                November 7, 2013

                I discovered your post on ZipOutputStream after I had finished writing my own code to create an epub (which is a zipfile by another name) from its constituent files. My code is more or less equivalent to yours, and it seems to run clean, but when I look at the epub zipfile after running the code, the file is there but it is length=0. Since there are no exceptions, I have been searching the web for posts like yours. I have run out of ideas. What might I have missed?

                - Chris Gage

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  August 18, 2013

                  Hi! I’ve been following your weblog for some time now and finally got the bravery to go ahead and give you a shout out from Lubbock Tx! Just wanted to say keep up the great job!

                  - www.barknetwork.com

                    Try DigitalOcean for free

                    Click below to sign up and get $200 of credit to try our products over 60 days!

                    Sign up

                    Join the Tech Talk
                    Success! Thank you! Please check your email for further details.

                    Please complete your information!

                    Get our biweekly newsletter

                    Sign up for Infrastructure as a Newsletter.

                    Hollie's Hub for Good

                    Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

                    Become a contributor

                    Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                    Welcome to the developer cloud

                    DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

                    Learn more
                    DigitalOcean Cloud Control Panel