Java Zip and Unzip Files and Folders

Here we will learn about how to zip and unzip files and folders in java.

If information contains redundant data it will be tough to store and transfer the data. So we will go for compression which will give efficient representation of the data. For zipping many algorithms are there.

Java provides the java.util.zip package for zipping and unzipping the files. The class ZipOutputStream will be useful for compressing. It is an output stream filter which will write files to any File output stream in zip format. The class ZipInputStream will be useful for decompressing. It is an input stream which will read files that are in zip format.

How to Zip Files in Java?

For zipping purpose we have many algorithms. If we are not mentioning any alogorithm through any method it will use default compression method that is DEFLATED compression. Deflated compression is almost near to Huffman coding.

Now we will see one example.

Problem: We want to zip the directory which has multiple files along with sub folders.

Solution: Zipping a file is very easy. But when we are zipping a folder which contains sub folders we should take care about the relative paths of files which have to be zipped.

For example take directory named as first which is located in E disk. It contains one subfolder along with multiple files. We have to zip it now.

Procedure :

Step 1: We should list out all files in the directory. listFiles() method will return total files (directories + files) in that directory. We can use this method to list out the total files. For this we have to check whether it is a directory or not. If it is a directory then again list out the files in that subdirectory. Continue this process until all files are listed out. This is recursive process.

Step 2: After listing out the files, we should create a file output stream for output zip folder. So that it will create output zip folder and write the contents to it.

Step 3: We should create a zip output stream which will write file contents to the file output stream in the format of zip.

Step 4: Now we have to zip each file in list according to their paths.

  • Create an input stream for a file. So that it can read file contents.
  • Create a zip Entry object for file with relative path only because if use absolute path it can’t find files so zipping is not possible. So that we can add this file to zip out stream. For adding putNextEntry() method of ZipOutputStream will be useful.
  • Now zip output stream will write these file contents in the format of zip to the file output stream.
  • Close zip entry and close file input stream

This is the process of zipping one file. So do the same for every file in the list.

Step 5: As zipping of all files is done. Now close all IO streams. Proper closing of IO streams will prevent the corruption of zip files.

Java Program to Zip files and Folders

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 Zipping{
	//create a list to store all files which have to be zipped
	static List<String> totalfiles = new ArrayList<String>();
	
	public static void main(String[] args) {
		
		try{
			File dir = new File("E://first");
			String dirPath= dir.getAbsolutePath();
			Zipping Obj = new Zipping();
			
			//List all files of input directory by calling listFiles method
			Obj.listFiles(dir);
			
			//create a new zip file in which all input files have to be zipped.
			File zipFile = new File("E:\\first.zip");
			
			//create output stream for the zipfile.
			FileOutputStream fos = new FileOutputStream(zipFile);
			
			//create zipoutputstream for the outputstream.
			ZipOutputStream zos = new ZipOutputStream(fos);
			
			byte[] buffer = new byte[1024];
			int len;
			
			//for each file in list do zipping process
			for (String path : totalfiles) {
				File ipfile = new File(path);
				
				//for zipping purpose we need only relative path. we shouldn't consider absolute path.
				//this will give relative path of the file which we are zipping now.
				String zippath = path.substring(dirPath.length() + 1, path.length());
				
				//we should create zipentry for each file.
				ZipEntry zen = new ZipEntry(zippath);
				
				//adding to zipoutputstream
				zos.putNextEntry(zen);
				
				FileInputStream fis = new FileInputStream(ipfile);
				
				while ((len = fis.read(buffer)) > 0) {
                  zos.write(buffer, 0, len);
                }
				
				//close all IO streams. Or else we may get corrupted zip files
				zos.closeEntry();
				fis.close();
				
				System.out.println(ipfile.getAbsolutePath()+"is zipped");
			}
			
			zos.close();
			fos.close();
		} catch (IOException e) {
			e.printStackTrace();
		} 
	}
	
	void listFiles(File dir) throws IOException {
		File[] files = dir.listFiles();
		
		for (File file : files) {
			//check a file is directory or not
			if (file.isDirectory()) {
				//if a directory then make recursive call to list out subfiles
				listFiles(file);
			} else {
				//if it is a file then add it's absolute path to the list.
				totalfiles.add(file.getAbsolutePath());
			}
		}
	}
}

Output

Java Program to Zip files and Folders

How to Unzip Files in Java?

Unzipping file means expanding the compressed information to make file as like its original form means before compression. For that ZipInputStream class will be useful.

Now we will see unzipping of a directory:

Suppose we want to decompress the zip folder named as first.zip which is located in E disk.

Procedure:

Step 1:  We should create file output stream for output folder. So that it can write files to that output folder. If output folder is not exists then create output folder. Use mkdirs() method. If any parent directories are not there then it will create them also.

Step 2: Here we have only one file that is zip file. So create one file input stream this is enough. This will read contents from zip file.

Step 3: Now create Zip input stream for this file input stream. This zip input stream can understand the zip file contents. It will change zip form to normal form.

  • Now these file contents has to be written to individual files. We should know which files are present in that zip file. So getNextEntry() method will return file which is present in zip file.
  • We should check the return value of the above method. Because if we are trying to unzip the corrupted zip file, it won’t be possible and if it is corrupted zip file then the above method will return the null value.
  • If it returns file value then we have to create file output steam with the relative path of that zippied file entry. So that we can unzip the file contents folder wise. Without disturbing the file organization. This file output stream will create the file and write the contents to that file. Use getParent().mkdirs() method to create parent folders of the output file.
  • Now write the file contents to the output stream so that it will write to file.

This is one file unzipping process. Repeat this process until all zipped files are unzipped.

Now we will see the program that will unzip the file contents.

Java Program to Unzip Files and Folders

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

public class Unzipping {
	public static void main(String[] args) {
		File opdir = new File("E:\\first");
		
		//we should check whether output exists or not
		if (!opdir.exists()) {
			//if not we should create. And if any parent folders not present then mkdirs() will create that parent folders
			opdir.mkdirs();
		}
		
		byte[] buffer = new byte[1024];
		int len;
		
		try {
			File ipfile = new File("E:\\first.zip");
			FileInputStream fis = new FileInputStream(ipfile);
			
			//zipinputstream will be useful for reading zipped contents.
			ZipInputStream zis = new ZipInputStream(fis);
			
			//each file in zip file we can get by getNextEntry() method.
			ZipEntry zen = zis.getNextEntry();
			
			//we should check whether it is corrupted zip file or not. if corrupted then zip entry will be null
			//we can't extract that corrupted files.
			while (zen != null) {
				String fileName = zen.getName();
				
				//files should be unzipped according their paths only.
				File newFile = new File(opdir + File.separator + fileName);
				
				//if any parent files are not present then we should create them also.
				new File(newFile.getParent()).mkdirs();
				
				FileOutputStream fos = new FileOutputStream(newFile);
				
				while ((len = zis.read(buffer)) > 0) {
					fos.write(buffer, 0, len);
				}
				
				System.out.println(fileName+" is unzippied now");
				
				//we should close io streams.
				fos.close();
				zis.closeEntry();
				zen = zis.getNextEntry();
			}
			
			zis.closeEntry();
			zis.close();
			fis.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

Output

Java Program to Unzip Files and Folders

Comment below if you have any queries or found any information incorrect in above tutorial for zip and unzip files in Java.

Leave a Comment

Your email address will not be published. Required fields are marked *