Java Programing laungage

java.util Projects

java.util Project 1

Unzip a ZIP File

In this page of the tutorials, we are going to learn How to extract a zip file? and How to retrieve elements from a zip format file. All questions related to ZIP file are solved through the following program.

Previous Home Next
adplus-dvertising

This program shows you how to extract files from a zip file in which many different files are stored in compressed format and make a single zip file. In this operation There are many type methods and APIs are used, which are explained as follow.

ZipEntry: This is the class of java.util.zip.*; package of Java, which is used to zip file entries.

ZipFile.entries(): This method of the Zip File class is used to get the files entries of the zip file format.

Enumeration.hasMoreElement(): This method is used to check whether more that one element are present or not for the zip file which is enumerated.

Enumeration.nextElement(): This method is used to give us the next elements from the list of the ZIP files.

Example


package r4r;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
public class unzipfiletest {
public static void main(String[] args){
unzipfiletest uzt = new unzipfiletest();
}
public unzipfiletest() { OutputStream ops = null; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try { System.out.print("Eneter zip file name for unzip: "); String sourcefilename = br.readLine(); if(!sourcefilename.endsWith(".zip")){ System.out.println("Wrong file name!"); System.exit(0); } else if(!new File(sourcefilename).exists()){ System.out.println("File not exist!"); System.exit(0); } ZipInputStream in = new ZipInputStream(new FileInputStream(sourcefilename)); ZipFile zf = new ZipFile(sourcefilename); int a = 0; for(Enumeration enm = zf.entries(); enm.hasMoreElements();){ String targetfile = enm.nextElement().toString(); ZipEntry ze = in.getNextEntry(); ops = new FileOutputStream(targetfile); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { ops.write(buf, 0, len); } a = a + 1; } if(a > 0) System.out.println("Files unzipped."); ops.close(); in.close(); } catch (IOException e) { System.out.println("Error: Unzip Operation failed!"); System.exit(0); } } }
Previous Home Next