Example of a Java ZIP file folder

Today we’re going to look at a sample Example of a Java ZIP file folder. We will also compress a folder and create a zip file using the Java program.

Java ZIP

java.util.zip.ZipOutputStream can be used to compress a file in ZIP format. A ZIP file can carry multiple entries and ZipOutputStream uses java.util.zip.ZipEntry to be a ZIP file entry.

Java ZIP File

Creating a zip archive for a file is very easy. We need to create a ZIP output stream object from the file output stream object of the target file. Next, we add a new zip entry to the zip output stream and use the FileInputStream to read the source file into the zip output stream object. Once we’re done writing, we need to close the zip entry and free up all resources.

Java Zip Folder

Compressing a directory is a bit complicated, first, we need to get the list of files as an absolute path. Then treat each of them separately. Now we have to add a ZipEntry into each file and use FileInputStream to read the contents of the source file into the ZipEntry corresponding to that file.

Example

Here is the Java program that shows how to compress a single file or folder in Java.

package com.HandyOpinion.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/HandyOpinion/sitemap.xml");
        String zipFileName = "/Users/HandyOpinion/sitemap.zip";
        
        File dir = new File("/Users/HandyOpinion/tmp");
        String zipDirName = "/Users/HandyOpinion/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


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

Notice that when I save the files in the zip directory, I print the absolute path. But when we add a zip entry we need to use a relative path from the directory, so that is the same directory structure is created when unzipping. That’s all for the Example of a Java ZIP file folder.

Next Articles

1. Java 8 Features 
2. Java 8 Functional Interfaces

Please share this post:
Posts created 52

Ask a Question

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

%d bloggers like this: