How to create ZIP file in Java


This article will help you to compress files in ZIP format and create its new ZIP file. To do this type of utilities Java comes with java.uptil.zip package to perform data compression in ZIP format.

In this example, I am going to read info.json file from the classpath location and add it into the Simple.zip file.

SimpleZipExample.java
package org.websparrow.zip;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class SimpleZipExample {

	public static void main(String[] args) {

		try {

			// Write all data into Simple.zip file
			ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream("Simple.zip"));

			// Read the file to add in Simple.zip file
			FileInputStream fileInputStream = new FileInputStream("info.json");

			// Change the entry name of file.
			ZipEntry zipEntry = new ZipEntry("company-information.json");

			// Begins writing a new ZIP file entry
			zipOutputStream.putNextEntry(zipEntry);

			byte[] buff = new byte[1024];
			int length = 0;

			// Writes an array of bytes to the current ZIP entry data.
			while ((length = fileInputStream.read(buff)) > 0) {
				zipOutputStream.write(buff, 0, length);
			}

			// close all streams
			fileInputStream.close();
			zipOutputStream.closeEntry();
			zipOutputStream.close();

			System.out.println("SUCCESS");

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

About the Author

Atul Rai
I like sharing my experiments and ideas with everyone by writing articles on the latest technological trends.