Java code to Decompress (Unzip) a file.

Already  we have seen , how to create a Compressed(Zip) file using java code. In that example we have compressed files and stored in a single Zip file. The logic given below will decompress the given zip file which is passed through command prompt. For compressing the file, we had used ZipOutputStream class in the package java.util.zip. The same package provides a ZipInputStream class for reading ZIP files. For creating an input stream for reading data from a ZIP file format, the following statements are used.

FileInputStream fis = new FileInputStream(“test.zip”);
ZipInputStream zis = new ZipInputStream(fis);

Next to read zip entries from the zip file using the getNextEntry method. There may be more than one zip entries. In our example two files are compressed, so two zip entries will be there. To read all the zip entries, until end of file is reached, use the following statements

ZipEntry zipEntry;
while((zipEntry = zis.getNextEntry()) != null) { ….. }, one of the method of ZipEntry getName() returns the name of ZipEntry in the zip file.

FileOutputStream fos = new FileOutputStream(zipEntry.getName());
while ((len = zis.read(buffer)) != -1) fos.write(buffer, 0, len);

The above lines create  the decompressed file by reading the contents from zip file until the end of file is reached for a particular zip entry. This is continued for all the zip entries in the zip file. The following statements are used for the said task.

The following code gets the input as zip file from command prompt and decompress all the files in the zip file. */

package com.javaonline;
import java.io.*;
import java.util.zip.*;

public class UnZipFile {
	   public static void main (String... cpv) {
	try {
	   byte[] buffer = new byte[1024];
	   if (cpv.length!=1){
		   System.out.println("Wrong Input . Syntax : java UnCompressZipFile test.zip");
		   System.exit(0);
	             }
	  String zipFileName=cpv[0];
	  if(!zipFileName.endsWith(".zip")) {
		  System.out.println("Zip File Not valid. eg. test.zip");
		  System.exit(0);
	  }
	  if(!new File(zipFileName).exists()){
		  System.out.println("Zip File does not exist");
		  System.exit(0);
	  }
	   FileInputStream fis = new    FileInputStream(zipFileName);
	   ZipInputStream zis = new   ZipInputStream(fis);
	   ZipEntry zipEntry;
	   while((zipEntry = zis.getNextEntry()) != null) {   //for each files in the zip
	            System.out.println("Extracting File : " +zipEntry);
	            int len;
	            // write the file to the disk
	            FileOutputStream fos = new   FileOutputStream(zipEntry.getName());
	            while ((len = zis.read(buffer))  != -1)   fos.write(buffer, 0, len);
	            fos.close();
	         }
	         zis.close();
	      } catch(Exception e) {
	         e.printStackTrace();
	      }
	   }
	}

 

Running  the program  will gives the below output.

unzip

You may also like

Leave a Reply