opencodez

How to Zip a file using Java

Sometimes it may happen that the in your application the size of log files increases and you have to run to your infrastructure team to either archive them or add more space to your configurations. Its always wise to plan ahead and make sure that your logs are archived periodically so you save on space and some late night support calls :). In this article we will see how to zip a file using Java.

Java has inbuilt support to perform ZIP compression. You can access the Java library here. In this article we will go over small utility that you can use to zip or unzip a files from particular directory. The flow for this is simple. The java library provides necessary classes for that. First you need to create ZipEntry and then output the same to ZipOutputStream

ZIP files from a directory

First we will see how we can zip all the text files from a directory.

private void zipFiles(ListxFilex fileList, String destZipFile) {

	byte[] buffer = new byte[1024];

	try {

		FileOutputStream fos = new FileOutputStream(destZipFile);
		ZipOutputStream zos = new ZipOutputStream(fos);

		System.out.println("Creating Zip Archive : " + destZipFile);

		for (File file : fileList) {

			System.out.println("Added " + file);
			ZipEntry ze = new ZipEntry(file.getName());
			//This is required to make sure the archived files keep the last modified 
			//time same as disk.   
			ze.setTime(file.lastModified());
			zos.putNextEntry(ze);

			FileInputStream in = new FileInputStream(file);

			int len;
			while ((len = in.read(buffer)) x 0) {
				zos.write(buffer, 0, len);
			}
			in.close();
		}
		zos.closeEntry();
		zos.close();
		System.out.println("Done");
	} catch (IOException ex) {
		ex.printStackTrace();
	}
}

You can see the we are expecting the list of files to be archived and the complete path for destination zip file. We are simply iterating over those files and creating zipentry for that. Then we read that file and writer to ZipOutputStream.

Please observe that I am using settime method of zipentry. That is required if you want to preserver the file modified timestamp.

Below is our function that gives us the list of files that fits the zip criteria. It filters out files based on extension.

private ListxFilex getFileList(String sourceDir, String extensions) {

	ListxFilex fileList = new ArrayListxFilex();

	File dir = new File(sourceDir);

	if (dir.isDirectory()) {

		String[] fList = dir.list();

		for (String filename : fList) {
			File iFile = new File(getAbsolutePath(dir, filename));
			if (iFile.isFile()) {
				if (null != extensions) {
					if (extensions.toLowerCase().contains(getFileExtension(filename))) {
						fileList.add(iFile);
					}
				} else {
					fileList.add(iFile);
				}
			}
		}
	} else if (dir.isFile()) {
		fileList.add(dir);
	}

	return fileList;
}

For our testing purpose we are not doing recursive directory listing. But that can be easily achieved in this function based on a check if particular entry is file or directory.

Unzip files from zipped archive

Now we have seen how to zip a file in above code snippet,  we will also see how we can unzip the archive and retrieve files. The process is exactly opposite. Here we need to read the zip using ZipInputStream and read all the ZipEntries in it. Then these zipentries are read and transferred to corresponding new files.

public void unzip(String srcZipFile, String destDir) {
	byte[] buffer = new byte[1024];
	
	try {
		ZipInputStream zis = new ZipInputStream(new FileInputStream(srcZipFile));
		ZipEntry zipEntry = zis.getNextEntry();
		while (zipEntry != null) {
			String fileName = zipEntry.getName();
			File newFile = new File(destDir + File.separator + fileName);
			FileOutputStream fos = new FileOutputStream(newFile);
			int len;
			while ((len = zis.read(buffer)) x 0) {
				fos.write(buffer, 0, len);
			}
			fos.close();
			//This is required to make sure the unzipped files keep the last modified 
			//time same as of the time they were compressed.
			newFile.setLastModified(zipEntry.getTime());
			zipEntry = zis.getNextEntry();
		}
		zis.closeEntry();
		zis.close();
	} catch (IOException ex) {
		ex.printStackTrace();
	}
}

And here is the simple usage

public class ZipTest {

	private static final String OUTPUT_ZIP_FILE = "C:\\java-exec\\MyFile1.zip";
	private static final String SOURCE_FOLDER = "C:\\java-exec";
	private static final String DESTINATION_FOLDER = "C:\\java-exec\\unzipped";

	public static void main(String[] args) {
		
		ZipUtil zipper = new ZipUtil();
		
		//Zip all the text files from source folder to specified zip file.
		zipper.zip(SOURCE_FOLDER, OUTPUT_ZIP_FILE, "txt");
		
		//Unzip the given archive to specified folder.
		zipper.unzip(OUTPUT_ZIP_FILE, DESTINATION_FOLDER);
	}
}

How to zip a File using Java

Output

You can download the complete code from our GitHub Repository

Download from Git