• Menu
  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

JavaBeat

Java Tutorial Blog

  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)

How To Create Zip File Using Java

April 21, 2014 //  by Krishna Srinivasan//  Leave a Comment

This example demonstrates how to create a zip file with the files and directories. Java provides java.util.zip package for compressing and packaging to zip file format. It is very common utility used by most of the applications. The key classes used in this package for packaging to zip format are ZipOutputStream, ZipEntry and Deflater. This example very well illustrates the packaging files and directories with path. Lets look at the example.

If you have any issues with the below code, please write it in the comments section. Note that, you have to provide the list of files and output file name for this program to work. I have added that code into the main method. Also read our previous articles working with java.util.zip and list contents from zip file.

CreateZipExample.java

package javabeat.net.zip;

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.Deflater;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * Create ZIP Example
 *
 * @author Krishna
 *
 */
public class CreateZipExample
{
	public static void main(String[] args) throws IOException{
		List files = new ArrayList();
		files.add(new File("TextFile.txt"));
		CreateZipExample.packageZipFile(new File("TestZip.zip"), files);
	}

	/**
	 * Packaging ZIP file
	 * @param output
	 * @param files
	 * @throws IOException
	 */
    public static void packageZipFile(File output, List files) throws IOException
    {
        System.out.println("Packaging To " + output.getName());

        //Create ZipOutputStream to create Zip file
        ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(output));
        zipOutputStream.setLevel(Deflater.DEFAULT_COMPRESSION);

        //Iterate the files and zipping it
        for (File file : files)
        {
            if (file.isDirectory())
            {
                zipDirectory(zipOutputStream, "", file);
            } else
            {
                zipFile(zipOutputStream, "", file);
            }
        }
        zipOutputStream.flush();
        zipOutputStream.close();
        System.out.println("Zipping Done");
    }

    private static String buildPath(String filePath, String fileVar)
    {
        if (filePath == null || filePath.isEmpty())
        {
            return fileVar;
        } else
        {
            return filePath + "/" + fileVar;
        }
    }

    /**
     * Zipping Directory
     *
     * @param zipOutStream
     * @param filePath
     * @param directory
     * @throws IOException
     */
    private static void zipDirectory(ZipOutputStream zipOutStream, String filePath, File directory) throws IOException
    {
        if (!directory.canRead())
        {
            System.out.println("Cannot read " + directory.getCanonicalPath() + " (maybe because of permissions)");
            return;
        }

        File[] files = directory.listFiles();
        filePath = buildPath(filePath, directory.getName());
        System.out.println("Adding Directory " + filePath);

        for (File source : files)
        {
            if (source.isDirectory())
            {
                zipDirectory(zipOutStream, filePath, source);
            } else
            {
                zipFile(zipOutStream, filePath, source);
            }
        }

        System.out.println("Leaving Directory " + filePath);
    }

    /**
     * Zipping individual file
     *
     * @param zipOutStream
     * @param filePath
     * @param file
     * @throws IOException
     */
    private static void zipFile(ZipOutputStream zipOutStream, String filePath, File file) throws IOException
    {
    	//Check if file can be read
        if (!file.canRead())
        {
            System.out.println("Cannot read file : " + file.getCanonicalPath());
            return;
        }

        System.out.println("Compressing File : " + file.getName());
        zipOutStream.putNextEntry(new ZipEntry(buildPath(filePath, file.getName())));

        FileInputStream fileInStream = new FileInputStream(file);

        byte[] bufferVar = new byte[4092];
        int byteVar = 0;
        while ((byteVar = fileInStream.read(bufferVar)) != -1)
        {
            zipOutStream.write(bufferVar, 0, byteVar);
            System.out.print('.');
            System.out.flush();
        }
        fileInStream.close();
        zipOutStream.closeEntry();
    }
}

Category: JavaTag: Java Zip

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Previous Post: « How To List Contents Of Zip File using Java
Next Post: How To Get Image Format Using Java »

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

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

Primary Sidebar

Follow Us

  • Facebook
  • Pinterest

FEATURED TUTORIALS

New Features in Spring Boot 1.4

Difference Between @RequestParam and @PathVariable in Spring MVC

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Introductiion to Jakarta Struts

What’s new in Struts 2.0? – Struts 2.0 Framework

JavaBeat

Copyright © by JavaBeat · All rights reserved
Privacy Policy | Contact