Compress Files To ZIP Format Using Java

This post demonstrates a simple example for how to compress your file and add to the ZIP file. Java has built-in API for compressing the files in ZIP format. It is very simple to read the files from your disk and writing to the destination ZIP file. It is straight forward.  The steps involved for writing to ZIP is:

  1. Read files using FileInputStream
  2. Then add the files to ZipEntry which is used for adding the list of files which are part of zip file
  3. Finally output the zip file by using the ZipOutputStream class

Lets look at the example:



public class CompressZipExample {

	public static void main(String[] args) {
		byte[] buffer = new byte[1024];

		try {
			FileOutputStream fileOutput = new FileOutputStream("");
			ZipOutputStream zipOutput = new ZipOutputStream(fileOutput);

			//Add a file entry to zip
			ZipEntry zipEntry = new ZipEntry("TestFile.txt");

			//Read the file from the given path
			FileInputStream fileInput = new FileInputStream("TestFile.txt");

			int length;
			while ((length = > 0) {
				zipOutput.write(buffer, 0, length);
			System.out.println("Files are added to zip!!");
		} catch (IOException ex) {


Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Pin It on Pinterest

Share This

Share this post with your friends!

Share This

Share this post with your friends!