UnZip

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
* @author Administrator
*
* 解压ZIP文件到指定目录
*/
public class UnZip {

public static void readZip(String toDir, String fileName) throws Exception {
String baseDir = toDir;
//Open Zip file given the specified File object (specified)指定的
ZipFile zfile = new ZipFile(fileName);
// Returns an enumeration of the ZIP file entries (enumeration)列表 (entries)条目
Enumeration zList = zfile.entries();
ZipEntry ze = null;
byte[] buf = new byte[1024];
int i = 0;
while (zList.hasMoreElements()) {
//从ZipFile中得到一个ZipEntry
ze = (ZipEntry) zList.nextElement();

if (ze.isDirectory()) {
//System.out.println("Dir: "+ze.getName()+" skipped..");
continue;
}
//System.out.println("Extracting:
// "+ze.getName()+"t"+ze.getSize()+"t"+ze.getCompressedSize());

//以ZipEntry为参数得到一个InputStream,并写到OutputStream中
OutputStream os = new BufferedOutputStream(new FileOutputStream(
getRealFileName(baseDir, ze.getName())));
// zfile.getInputStream(ze)
//Returns an input stream for reading the contents of the specified zip file entry.
//读取指定的ZIP文件内容,返回一个输入流
InputStream is = new BufferedInputStream(zfile.getInputStream(ze));
int readLen = 0;
if (null!=is){
while ((readLen = is.read(buf, 0, 1024)) != -1) {
os.write(buf, 0, readLen);
}

is.close();
os.close();
}

//System.out.println("Extracted: "+ze.getName());
}
zfile.close();
}
// Parser Zip file name And maker directory
private static File getRealFileName(String baseDir, String absFileName) {
String[] dirs = absFileName.split("/");
// System.out.println(dirs.length);
File ret = new File(baseDir);
//System.out.println(ret);
if (dirs.length > 1) {
for (int i = 0; i < dirs.length - 1; i++) {
ret = new File(ret, dirs[i]);
}
}
//if not exists directory make it
if (!ret.exists()) {
ret.mkdirs();
}
ret = new File(ret, dirs[dirs.length - 1]);
return ret;
}


public static void main(String[] str){

String todir="d:aa";
String filename="d:bb.zip";
try {
UnZip.readZip(todir,filename);
} catch (Exception e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
}

}

[@more@]

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/557469/viewspace-893752/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/557469/viewspace-893752/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值