How can I create a zip file from a set of files?
Author: Deron Eriksson
Description: This Java tutorial describes how to create a zip file from a set of files.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)


Page:    1 2 >

This tutorial will demonstrate how to create a zip file for a set of files. The tutorial project has the following structure:

'testing' project

We will zip up the following files in the project:

file1.txt
file2.txt
folder/file3.txt
folder/file4.txt
f1/f2/f3/file5.txt

The ZipFiles class creates a FileOutputStream to 'atest.zip', the name of the zip file to create. It creates a ZipOutputStream object based on the FileOutputStream. It then calls its addToZipFile() method to write each file to the zip file.

In addToZipFile(), we create a FileInputStream to read from the specified file. We create a ZipEntry object for the file and tell the ZipOutputStream that we'll be writing a ZipEntry to it via the call to putNextEntry(). We read the file contents from the FileInputStream and write the file contents to the ZipOutputStream.

ZipFiles.java

package test;

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

public class ZipFiles {

	public static void main(String[] args) {

		try {
			FileOutputStream fos = new FileOutputStream("atest.zip");
			ZipOutputStream zos = new ZipOutputStream(fos);

			String file1Name = "file1.txt";
			String file2Name = "file2.txt";
			String file3Name = "folder/file3.txt";
			String file4Name = "folder/file4.txt";
			String file5Name = "f1/f2/f3/file5.txt";

			addToZipFile(file1Name, zos);
			addToZipFile(file2Name, zos);
			addToZipFile(file3Name, zos);
			addToZipFile(file4Name, zos);
			addToZipFile(file5Name, zos);

			zos.close();
			fos.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public static void addToZipFile(String fileName, ZipOutputStream zos) throws FileNotFoundException, IOException {

		System.out.println("Writing '" + fileName + "' to zip file");

		File file = new File(fileName);
		FileInputStream fis = new FileInputStream(file);
		ZipEntry zipEntry = new ZipEntry(fileName);
		zos.putNextEntry(zipEntry);

		byte[] bytes = new byte[1024];
		int length;
		while ((length = fis.read(bytes)) >= 0) {
			zos.write(bytes, 0, length);
		}

		zos.closeEntry();
		fis.close();
	}

}

(Continued on page 2)

Page:    1 2 >