Jerry Jacob's Blog

Create zip files in Java

Posted in Java/ J2EE by jerlinworld on January 11, 2012

The output of the below Java program will be the creation of a zip file inside c:/ with the name test.zip
Taken from http://extreme-java.com



package com.example;
 
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
 
/** This class is a Java tutorial for creating zip file
 * 
 * @author Extreme Java
 */
public class Test{
 
	/** The method creates zip file and also creates an entry inside it
	 * 
	 * @param args is the command line arguments
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException  {
		//create a file output stream
		FileOutputStream zipFOS = new FileOutputStream("c://test.zip");
 
		//create a zip output stream from the file output stream created above.
		//zip output stream decorates file output stream
		ZipOutputStream zipoutStream = new ZipOutputStream(zipFOS);
 
		//creates an zip entry. You can create as many entries as you wish
		//Each entry represent a file with in the zip archive
		ZipEntry zipEntry = new ZipEntry("source1");
 
		//put the zip entry create above into the zip file
		zipoutStream.putNextEntry(zipEntry);
 
		//write some text into the zip entry created above.
		//Whatever is written will be added to last added zip entry
		zipoutStream.write(1);
 
		//close the zip entry.
		zipoutStream.closeEntry();
 
		//Finish the creation of zip file.
		zipoutStream.finish();
 
		//close the file output stream
		zipFOS.close();
 
		//close the zip output stream
		zipoutStream.close();
	}
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: