Zippity Do Dah, Zipping with Java, Yay!

My oh my what a wonderful code day! Welcome to another entry of my blog and I hope you have enjoyed your stay. Before we cover todays topic of creating zip files in Java I wanted to thank everyone who has subscribed to my blog and added links through their websites. I appreciate the support and enjoy bringing you on a journey through this vast programming world. We have tamed the beasts known as C++ and C#, ran along the open plains with VB.NET, explored the mountains with PHP (yeah that old fart with the white beard saying something about middle earth) and even sailed the dark oceans of Java. So climb the masts and set sail because we are going on another sailing journey right here on the Programming Underground!

Todays entry covers creating basic zip files through Java. Now you don’t need anything extra in the way of plugins, packages, downloads or anything. Zip file creation is part of the standard package that comes with the SDK. Our example below is going to do a few things for us. First it is going to create a standard swing application with a button in the middle. This button is going to trigger a file chooser dialog which will allow the user to select some files from a directory. After the user has chosen the files to zip, it will create a file called “” and drop it in the same directory as where the user chose the files from. Pretty much just like Windows does when you choose “Send to Zip” from the context menu in windows explorer.

So lets take a look at the Java code. Please be sure to read through the in code comments to follow along with what I am doing. Also pay attention to how I divided the tasks. Notice I put the zipping code in its own function and pass along the file path and the list of files. I did this because I wanted to make it easy for myself later to reuse this function in other projects.

import javax.swing.*;
import java.awt.event.*;

public class zip extends JFrame implements ActionListener {
	// Create our zip button to kick off the zipping
	JButton zipButton = new JButton("Zip Files");

	public static void main(String args[]) {
		// Setup and show our frame
		zip frame = new zip();
		frame.setTitle("Zip Utility Example");

	// When we create the class, place the button and attach its event.
	// Then we add it to the form window.
	public zip() {

	// This is an event handler that handles our button press
	public void actionPerformed(ActionEvent e) {

		// If the zipButton was pressed, launch our file chooser
		// Set it to allow multiple file selections
		if (e.getSource() == zipButton) {
			JFileChooser fc = new JFileChooser();

			// Launch the dialog and if they choose to open files, call our zip function.
			int optionval = fc.showDialog(this,"Zip Files");

			if (optionval == JFileChooser.APPROVE_OPTION) {
				try {
					// Call our zip file function along with the files the
					// user chose from the file chooser dialog

					zip(fc.getCurrentDirectory() + "/",fc.getSelectedFiles());
					JOptionPane.showMessageDialog(null, "Files have been zipped!");
				catch (IOException exception) {
					JOptionPane.showMessageDialog(null, "Error in zipping files, please try again.");

	// This function controls our zipping of files. It loops through the files array passed
	// into the function and 1) Creates a file zip entry for each file and 2) Opens each file and 
	// transfers it to the zip file. It will overwrite the zip file of the same name if it exists.

	public void zip(String zipFilePath, File[] Files) throws IOException, FileNotFoundException {
		// Create our zip file
		ZipOutputStream zipfile = new ZipOutputStream(new FileOutputStream(zipFilePath));

		// Loop through the files passed in
		for (int i = 0; i < Files.length; i++) {
			// Open the current file and add an entry to the zip
			FileInputStream filetozip = new FileInputStream(Files[i].toString());
			zipfile.putNextEntry(new ZipEntry(Files[i].getName()));

			// Loop through the contents writing it to the zip file output stream.
			int len;
			byte[] buffer = new byte[1024];

			while ((len = > 0) {

			// Close the entry and the current file.
		// When done, close the zip file.

So I start off by importing the packages I need to access the zip functionality as well as file handling functions. The zip file functionality is in and this package contains the classes ZipEntry, ZipOutputStream etc used by our zip() function.

Next I start a class that sets up a JFrame with a JButton on it. The button has a button handler (actionPerformed) that opens a JFileChooser dialog box allowing the user to select multiple files to be included in the zip. This process is very similar to using a openfiledialog control in the .NET languages. Once the user chooses the files they want to include, it passes the name of the zip file (in this case “” and the current directory they chose the files from) and all the files to include in the zip to the zip() function for zipping.

The heart of this program is the zip() function where we do the following…

1) We open a ZipOutputStream object using the file name portion of the path passed to the function.
2) We start a loop through the array of File objects. For each File object we write an entry to the zip file, open the file, read its contents, write those contents to the zip file, close the entry and close the file.
3) Then we move onto the next file until all files have been exhausted.
4) Lastly we close the ZipOutputStream.

After this process is done, we return back to the actionPerformed() event handler where we notify the user if the process was successful or not.

Notice that the zip function throws two exceptions. This is because of file handling we are doing in the function. So back in the actionPerformed() method we setup some try catch error handling to detect if there was an IOException of some sort (like a file not found or not accessible) and let the user know the file zipping failed worse than Elizabeth Taylor and her 7 previous marriages.

This project is just an example of how you can go about creating a nice zip utility using Java with little work and effort. You could use this example as the base for zipping functionality in a larger project like an email program for collecting files, zipping and then emailing or a project like file storage using compression (the example has no compression, but you can explore the package and there are ways to implement compression with a few more function calls).

I hope you had a great time playing around with zip files using the demo. Feel free to use the code as you see fit and if you want more coding tips, tutorials and snippets, be sure to explore the Dream.In.Code web boards and tutorials sections. Thanks again for reading! 🙂

About The Author

Martyr2 is the founder of the Coders Lexicon and author of the new ebooks "The Programmers Idea Book" and "Diagnosing the Problem" . He has been a programmer for over 25 years. He works for a hot application development company in Vancouver Canada which service some of the biggest tech companies in the world. He has won numerous awards for his mentoring in software development and contributes regularly to several communities around the web. He is an expert in numerous languages including .NET, PHP, C/C++, Java and more.