How to zip files by Java?


In Java java.util.zip package provide below classes and api’s to convert files to zip file.

ZipOutputStream: This class implements an output stream filter for writing files in the ZIP file format.

ZipEntry: Class is used for zip entry.

In below example will show  to make single zip for multiple files .

package test.facingissesonit.zip;

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

public class TestZip {

	public static void main(String[] args) {
		TestZip testZip = new TestZip();
		List<File> sourceFiles = new ArrayList<File>();
		sourceFiles.add(new File("C:\\test.xls"));
		sourceFiles.add(new File("C:\\Contact.txt"));
		testZip.convertFilesToZip(sourceFiles,
				new File("C:\\Ouput.zip"));

	}

	public void convertFilesToZip(List<File> sourceFiles, File outputZip) {
		FileOutputStream fos = null;
		ZipOutputStream zos = null;
		ZipEntry ze = null;
		FileInputStream in = null;
		byte[] buffer = new byte[1024];

		try {

			fos = new FileOutputStream(outputZip);
			// Crate Zip output stream to write zip file
			zos = new ZipOutputStream(fos);
			if (sourceFiles != null && sourceFiles.size() > 0) {
				// make netry of all files which want to zip
				for (File sourceFile : sourceFiles) {
					// if want to zip on same directory then use filename or
					// define some path
					ze = new ZipEntry(sourceFile.getName());
					zos.putNextEntry(ze);
					// read source file
					in = new FileInputStream(sourceFile);
					// read in buffer to write in zip file
					int len;
					while ((len = in.read(buffer)) > 0) {
						zos.write(buffer, 0, len);
					}

					in.close();
				}
			}

			System.out.println("Zip Done for files");

		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			if (zos != null) {
				try {
					// Close Zip file entry and release all resources
					zos.closeEntry();
					zos.close();
				} catch (IOException ex) {
					ex.printStackTrace();
				}
			}
		}

	}

}

More Sample Code

For more java and JDBC codes follow below links

About Saurabh Gupta

My Name is Saurabh Gupta, I have approx. 10 Year of experience in Information Technology World manly in Java/J2EE. During this time I have worked with multiple organization with different client, so many technology, frameworks etc.
This entry was posted in Java and tagged , . Bookmark the permalink.