Home > Java Core > Java I/O > Java Utility To Compress Files/Folder In Zip Format

Java Utility To Compress Files/Folder In Zip Format


Java provides “java.util.zip” library to compress files/folder in zip format.

Steps to follow –

1. Take folder/files path as input.
2. Create a ZipOutputStream
3. Check if folder is empty or not. If the folder is empty, we will simply add the empty folder in zip, else we will read all the files and will add every files to zip.

package com.jkoder;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipFolderExample {
	private final static String INPUT_FOLDER_NAME = "/opt/dev/report/";
	private final static String ZIP_FILE_NAME = "/opt/dev/report.zip";
	public static void main(String a[]) {
		try {
			File inFolder = new File(INPUT_FOLDER_NAME);
			File outFolder = new File(ZIP_FILE_NAME);
			ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
					new FileOutputStream(outFolder)));
			BufferedInputStream in = null;
			byte[] data = new byte[1000];
			String files[] = inFolder.list();
			if(inFolder.list().length > 0){
				for (int i = 0; i < files.length; i++) {
					in = new BufferedInputStream(new FileInputStream(inFolder
							+ "/" + files[i]), 1000);
					out.putNextEntry(new ZipEntry(files[i]));
					int count;
					while ((count = in.read(data, 0, 1000)) != -1) {
						out.write(data, 0, count);
				out.putNextEntry(new ZipEntry(INPUT_FOLDER_NAME));
		} catch (Exception e) {

In the next example we will show “How to decompress a zip file in java”.