How to zip files by Java?

In Java 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 .


import java.util.ArrayList;
import java.util.List;

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"));
				new File("C:\\"));


	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());
					// read source file
					in = new FileInputStream(sourceFile);
					// read in buffer to write in zip file
					int len;
					while ((len = > 0) {
						zos.write(buffer, 0, len);


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

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



More Sample Code

For more java and JDBC codes follow below links


About Saurabh Gupta

My Name is Saurabh Gupta, I have approx. 11 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.

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s