ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

How to create a Zip File in Java ?.

Updated on September 17, 2014


In this tutorial, you will learn how to create a zip file in Java. Java has very vast API to deal with various such problems. Java API contains various classes and streams that help us in creating a zip file. A zip file is nothing but a compressed file saving memory as well as a handy format in storing multiple files together. In this simple tutorial we will create a zip file by name through Java code. This zip file will contain two already created text files such as sample1.txt and sample2.txt. You can create zip with any of the file format files into it. This Java utility is really a good tool in creating a zip file. You can use this source code in creation of various tools which outputs multiple files. The tutorial contains a video tutorial and highly commented Java code below. Just browse and watch video tutorial to understand zip file creation concept through Java.

Java video tutorial - How to create a zip file in Java.

Java source code - How to create a zip file in Java.

// Step 1 - Import classes present in Java API such as File, FileInputStream,
// FileOutputStream, ZipEntry and ZipOutputStream.

// Step 2 - Create a Java class CreateZip having a main method. This method
// is the starting point of execution.
public class CreateZip {

   public static void main(String[] args) {

	try {
	// Step 3 - In order to create a zip file, we have to create a FileOutputStream
	// which will refer zip files as 
	FileOutputStream fos = new FileOutputStream("");
	// Step 4 - In order to write contents/files in, we have to create a
	// ZipOutputStream. This input stream helps in writing files to 
	// with the help of FileOutputStream created above. 
	ZipOutputStream zos = new ZipOutputStream(fos);

	// Step 5 - Create two Strings pointing to files with actual location appended to it. 
	// Lets say we want to create a zip file holding sample1.txt and sample2.txt.  
	String file1 = "sample1.txt";
	String file2 = "sample2.txt";

	// Step 6 - In order to add these two text files to file, we call a static method
	// that takes in a ZipOutputStream and file to add into it. We call this method twice to add
	// one file at a time to zip. Initially, there are only two files sample1.txt and sample2.txt as 
	// shown in first fig. below
	add( zos , file1 );
	add( zos , file2 );

	// Step 14 - Close ZipOutputStream and FileOutputStream after creating zip file.
	} catch (Exception e) {
	}  	}

        // Step 7 - Create a static method by name add. It takes ZipOutputStream and file location + file name.
	public  static void add(ZipOutputStream zos, String fileName) throws Exception {

	// Step 8 - Create a File from the fileName String passed to it.
	File file = new File(fileName);
	// Step 9 - Create a FileInputStream with the file created above. 
	FileInputStream fis = new FileInputStream(file);
	// Step 10 - In order to create a zip file with multiple files, we have to create ZipEntry for each file.
	// ZipEntry is created for each and every file to be added. This ZipEntry instance takes 
	// in a fileName passed to method. ZipOutputStream has a method putNextEntry which 
	// takes in a ZipEntry instance for each and every file we want to put in zip.
	ZipEntry zipEntry = new ZipEntry(fileName);

	// Step 11 - After placing a ZipEntry in ZipOutputStream, now its time to put actual contents
	// of file to zip. Create a byte array taking 1024 size of array. 
	byte[] bytes = new byte[1024];
	int length;
	// Step 12 - Using ZipOutputStream's write method write contents of file to ZipEntry file. We use while 
	// loop to write contents of file to zip till file is completely written.
	while ((length = >= 0) {
		zos.write(bytes, 0, length);
	// Step 13 - Close ZipEntry instance and FileInputStream.

Let say we want to create a zip file by name This zip file must contain two files such as sample1.txt and sample2.txt. Before running the above Java program there are only two sample txt files as shown below.

Before creation of zip file

After running CreateZip Java class, it creates a zip file by name This zip file has two files such as sample1.txt and sample2.txt. After running above Java program structure of file system changes and it creates as shown below.

After creation of zip files

Output of the program -

After running CreateZip class, it creates a zip file by name Let's open this zip file as shown in below image. It contains two text files such as sample1.txt and sample2.txt. Thus, it conforms creation of zip file through Java code demonstrated above.

Contents of zip file ""


    0 of 8192 characters used
    Post Comment

    No comments yet.


    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at:

    Show Details
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the or domains, for performance and efficiency reasons. (Privacy Policy)
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)