Read the Contents of a Zip File Using the Package

Read the Contents of a Zip File Using the Package

This example code extracts the content of a zip file (the name of the zip file is supplied in args[0]). First, open the zip file using ZipFile class, then loop through all entries in the zip file and extract the content. If one entry is a directory then create it.

 import*;import java.util.*;import*;public class ReadZipFile{	public static void main(String args[]) throws Exception{//first argumentis zip file name		if(args.length==0){			System.out.println("Zip file name is missing");			return;		}		ZipEntry ze;		byte buf[];		FileOutputStream fout;		File dir;		ZipFile zf=new ZipFile(args[0]);		Enumeration zentries=zf.entries();		while(zentries.hasMoreElements()){			ze=(ZipEntry)zentries.nextElement();			System.out.println(ze.getName());			if(!ze.isDirectory()){				buf=new byte[(int)ze.getSize()];	//create buffer to store data				zf.getInputStream(ze).read(buf);	//read data from file in zip file				fout=new FileOutputStream(ze.getName());				fout.write(buf);	//write data to file				fout.close();			}else{				dir=new File(ze.getName());	//create directory				dir.mkdir();			}		}		zf.close();	}}


Share the Post: