How to compress files in ZIP format

Java comes with “java.util.zip” library to perform data compression in ZIp format. The overall concept is quite straightforward.

  1. Read file with “FileInputStream
  2. Add the file name to “ZipEntry” and output it to “ZipOutputStream

1. Simple ZIP example

Read a file “C:\\spy.log” and compress it into a zip file – “C:\\MyFile.zip“.


package com.mkyong.zip;

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

public class App 
{	
    public static void main( String[] args )
    {
    	byte[] buffer = new byte[1024];
    	
    	try{
    		
    		FileOutputStream fos = new FileOutputStream("C:\\MyFile.zip");
    		ZipOutputStream zos = new ZipOutputStream(fos);
    		ZipEntry ze= new ZipEntry("spy.log");
    		zos.putNextEntry(ze);
    		FileInputStream in = new FileInputStream("C:\\spy.log");
   	   
    		int len;
    		while ((len = in.read(buffer)) > 0) {
    			zos.write(buffer, 0, len);
    		}

    		in.close();
    		zos.closeEntry();
           
    		//remember close it
    		zos.close();
          
    		System.out.println("Done");

    	}catch(IOException ex){
    	   ex.printStackTrace();
    	}
    }
}

2. Advance ZIP example – Recursively

Read all files from folder “C:\\testzip” and compress it into a zip file – “C:\\MyFile.zip“. It will recursively zip a directory as well.


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

public class AppZip
{
    List<String> fileList;
    private static final String OUTPUT_ZIP_FILE = "C:\\MyFile.zip";
    private static final String SOURCE_FOLDER = "C:\\testzip";
	
    AppZip(){
	fileList = new ArrayList<String>();
    }
	
    public static void main( String[] args )
    {
    	AppZip appZip = new AppZip();
    	appZip.generateFileList(new File(SOURCE_FOLDER));
    	appZip.zipIt(OUTPUT_ZIP_FILE);
    }
    
    /**
     * Zip it
     * @param zipFile output ZIP file location
     */
    public void zipIt(String zipFile){

     byte[] buffer = new byte[1024];
    	
     try{
    		
    	FileOutputStream fos = new FileOutputStream(zipFile);
    	ZipOutputStream zos = new ZipOutputStream(fos);
    		
    	System.out.println("Output to Zip : " + zipFile);
    		
    	for(String file : this.fileList){
    			
    		System.out.println("File Added : " + file);
    		ZipEntry ze= new ZipEntry(file);
        	zos.putNextEntry(ze);
               
        	FileInputStream in = 
                       new FileInputStream(SOURCE_FOLDER + File.separator + file);
       	   
        	int len;
        	while ((len = in.read(buffer)) > 0) {
        		zos.write(buffer, 0, len);
        	}
               
        	in.close();
    	}
    		
    	zos.closeEntry();
    	//remember close it
    	zos.close();
          
    	System.out.println("Done");
    }catch(IOException ex){
       ex.printStackTrace();   
    }
   }
    
    /**
     * Traverse a directory and get all files,
     * and add the file into fileList  
     * @param node file or directory
     */
    public void generateFileList(File node){

    	//add file only
	if(node.isFile()){
		fileList.add(generateZipEntry(node.getAbsoluteFile().toString()));
	}
		
	if(node.isDirectory()){
		String[] subNote = node.list();
		for(String filename : subNote){
			generateFileList(new File(node, filename));
		}
	}
 
    }

    /**
     * Format the file path for zip
     * @param file file path
     * @return Formatted file path
     */
    private String generateZipEntry(String file){
    	return file.substring(SOURCE_FOLDER.length()+1, file.length());
    }
}

Output


Output to Zip : C:\MyFile.zip
File Added : pdf\Java-Interview.pdf
File Added : spy\log\spy.log
File Added : utf-encoded.txt
File Added : utf.txt
Done
Follow Up
You may interest at this – How to decompress it from a Zip file

Reference

  1. Compressing and Decompressing Data Using Java APIs

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
Hannes S
Guest
Hannes S

“great” example…Sry, but this example creates invalid ZIP files. Within ZIP files you should ALWAYS use forward slashes for paths – this is described within the ZIP standard (https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT). this example creates backward slashes for paths on windows file systems. I wouldn’t blame you, if you were using unix, but obviously you ARE using windows.
Please adapt this to avoid others creating invalid ZIPs.

Mohammad
Guest
Mohammad

Hi, thank you a lot, But It Has A Problem!!!
if we get it an empty folder, it will throw exception, and also, if we have an empty folder in another folder, it doesn’t create that empty folder!

Sarthak
Guest
Sarthak

How can I create self Extract executable file using java ? any idea.

Joseph Selvaraj
Guest
Joseph Selvaraj

Hi Kong, I tested this code , In last line “SOURCE_FOLDER.length()+1 ” , +1 is not required. Am I right?

Koushik Roy (bOyInDBoX)
Guest
Koushik Roy (bOyInDBoX)

I have a requirement to zip an XML file generated in the same code flow. I am marshalling a java object to outputstream. But I don’t want to write the XML file. Because all I need is the zip file, XML file is not being used later.

I was trying to discover if we can directly zip the outputstream of xml into a zip file without creating the intermediate XML file.

My last option would be, creating the XML file, then creating the ZIP file from it and then deleting the XML file.

Please let me know if this is possible.

varun
Guest
varun

Hi did you get the code? if you can you please share the code i am also facing the same problem please hep.

Vijayaraj A
Guest
Vijayaraj A

hi friends ,i need java code for report generation with ms Access connectivity…help me..!

Praveen
Guest
Praveen

Hello Sir,
I have a requirement where client can download all uploaded file from server.
I have done downloading for single file. But i am not able to allow user to download all file at a single click
Please Help me with this. all files are image file and i am suppose to zip it and allow download to user pc.
Thank you
Praveen

Mohammed Amine
Guest
Mohammed Amine

Hi mkyong thank you for this section it is interesting but the code does not work it gives an empty archive :(

milan
Guest
milan

I am getting error on this code…..like main class not found please help me fast please …. :(

trackback
Java?????? | ???cn

[…] How To Compress Files In ZIP Format useless […]

YoYo
Guest
YoYo

If i have a list of files, and i would like to rename it beofre zip it up, how could that be done?Can anyone advise? Many Thanks.

trackback
Compactar arquivo (ou texto) no formato zip com java | Desenvolvimento Web

[…] pesquisava sobre o assunto, acabei encontrando esse post com um exemplo parecido com este e outro exemplo mais avançado. Vale a pena conferir […]

rajesh
Guest
rajesh

jogadulal es tarah program mat write kiya karo

Pankaj
Guest
Pankaj

The closeEntry() call should be inside the for loop in compressing directory.

site
Guest
site

The design for the blog is a tad off in Epiphany. Nevertheless I like your website. I may need to use a normal web browser just to enjoy it.

GuoTao
Guest
GuoTao

Hi Yong,
it’s necessary to considered that compressing directories which are empty in the example of ‘Advance ZIP example – Recursively’.
thank you for sharing,I like the platform.

nagarjuna
Guest
nagarjuna

can u send me the program for created zip file is automatically send to mail through our gmail……….

Give me reply to my mail nagarjuna.gottimukkala@gmail.com

Khaled
Guest
Khaled

You can use Java mail to create an e-mail, attach that zip file and send it to that designated address.

abaynew
Guest
abaynew

hllow dears

how to convert java code into jara files

trackback
Java I/O Tutorials

[…] Compress files in ZIP format […]

trackback
How to decompress files from a ZIP file | Java

[…] Written on January 22, 2010 at 12:45 pm by mkyong In previous article, you learn about how to compress files to a zip file format. In this article you will learn how to unzip […]

Monty
Guest
Monty

Thank you!

Sachin
Guest
Sachin

Awesome example
I have found a issue when zip CSV file or zip
zip file.some time (1/100) zip file write byte in zip never end.
How is posible.

Andrew
Guest
Andrew

Thank You

John Zhou
Guest
John Zhou

You are awesome!

Reyner
Guest
Reyner

Thank you really help my assignment , youre the best Sir!!

im from indonesia, informatic engineering student

Anjaneya
Guest
Anjaneya

Thanks man …it helped me a lotttttttttttttt…………………..!

Mazenization
Guest
Mazenization
Thank You, Mr Kong for sharing the code. I have re-coded the code to fit my requirements, and I’d like to share it. Below is a class called ZipFiles offers two static methods for zipping/unzipping (one file or one folder with files, empty folders, and non empty folders. ========================================== package com.mazenization.testZip; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; public class ZipFiles { private static ArrayList fileList = null; private static String sourceFolder = null; public static boolean zip(String zipFile, String source) throws IOException{ byte[] buffer = new byte[1024]; FileInputStream fis =… Read more »
Coder12334576
Guest
Coder12334576

Thanks for the code – this does not fail on empty folders like mkyong’s does, I wish he would update his example. You have an error in your code though – lowercase ‘s’ in String.

Deepak PK
Guest
Deepak PK

Sir your code made my app possible. thanks alot :)
here is the link to my app :
http://sourceforge.net/projects/zipbox/

Kruspe
Guest
Kruspe

You are GOD ! Your site is one of the best tutorial’s sites ! You have done everting :-D

java apps
Guest
java apps

Superb tutorial! You explained everything in a very simple way.helped a lot to a newbie like myself

Dhanaprakash
Guest
Dhanaprakash

Superb.. Thanks a lot for sharing …
It works Perfectly for me.. :)