How can I create an uncompressed zip file from a set of files?
Author: Deron Eriksson
Description: This Java tutorial describes how to create an uncompressed 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 >

In another tutorial, we saw how we could create a zip file from a set of files. Zip compression can take a certain amount of time to perform. On occasion, you may want to create a zip file to store multiple files in a single file, but you might want to avoid the time required to compress the files. As an example, if you are zipping a set of large files that have already been compressed, it would make sense to avoid compression in the big zip file that you're creating. To demonstrate how to do this, we'll use the following project.

'testing' project

In the previous tutorial, we used the ZipFiles class to create a compressed zip file from a set of files. In this tutorial, we'll create an 'uncompressed-test.zip' file and add the following line to the ZipFiles class:

	zos.setLevel(ZipOutputStream.STORED);

We set the compression level on the ZipOutputStream to be STORED, which means that the files should be stored uncompressed. The rest of ZipFiles was described in the previous tutorial, so I'll just list the class here:

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("uncompressed-test.zip");
			ZipOutputStream zos = new ZipOutputStream(fos);

			// This sets the compression level to STORED, ie, uncompressed
			zos.setLevel(ZipOutputStream.STORED);

			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 >