Create ZIP file in Java

Overview

A Zip file is an archive archived file format that contains one or more files or directory. You can read more about it in Wikipedia. As a developer we often need to create ZIP file in Java to compress one or more files.

In this post, we will learn to create a Zip file using native way. With this example, you don’t need to add any third-party libraries.

1. Zip a single file

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

/**
 * Creates the Zip File.
 */
public class ZipFileCreator {
	/**
	 * Adds a single file into zip.
	 * 
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		FileOutputStream fileOutputStream = null;
		ZipOutputStream zipOutputStream = null;
		FileInputStream fis = null;
		try {
			fileOutputStream = new FileOutputStream("singlefile.zip");
			zipOutputStream = new ZipOutputStream(fileOutputStream);
			File myFileToZip = new File("myfile.png");
			fis = new FileInputStream(myFileToZip);
			ZipEntry ze = new ZipEntry(myFileToZip.getName());
			zipOutputStream.putNextEntry(ze);
			/*
			 * Initializing byte array with 1024 byte so that if the input stream is too
			 * large then it will not load all the bytes into the memory. If we add too low
			 * like, 10 or 100 then, the loop will take most of its time
			 */
			byte[] byteArray = new byte[1024];
			int size = 0;
			while ((size = fis.read(byteArray)) != -1) {
				zipOutputStream.write(byteArray, 0, size);
			}
			zipOutputStream.closeEntry();
			System.out.println("Done... Zipped files...");
		} finally {
			if (fis != null)
				fis.close();
			if (zipOutputStream != null)
				zipOutputStream.close();
			if (fileOutputStream != null)
				fileOutputStream.close();
		}
	}
}

Things to remember

You should always close your ZipOutputStream after finishing your task. If you miss it to close then you will get an error while opening the Zip.

Conclusion

In this post we learned to create Zip file in Java by adding single file into it.


Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments