Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Beginner
Jul 26, 2002

Read the Contents of a Zip File Using the java.util.zip 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 java.util.zip.*;
import java.util.*;
import java.io.*;

public class ReadZipFile{
	public static void main(String args[]) 
throws Exception{//first argument
is 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();
	}
}
Tien Nguyen
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date