没什么好说的,直接上代码分析
package com.app.zip;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* @author 黄经理
* 解压zip文件代码
* 说明:我在此处解压的是Tomcat的zip格式的压缩包
* 为了操作成功,在文件的路径中尽量不要出现中文
*/
public class UnZip {
public static void main(String[] args) {
String source="E:\\tomcat.zip";
File sourceFile=new File(source);
String targetFile="E:\\zip";
unzip(sourceFile,targetFile);
}
/**
* @param sourceFile 源文件
* @param targetFile 目标文件
*/
public static void unzip(File sourceFile, String targetFile) {
//判断源文件是否存在
if(!sourceFile.exists()) {
//源文件不存在 抛出一个异常
throw new RuntimeException(sourceFile.getPath()+"路径下的文件不存在");
}
/* 源文件存在 开始解压
* ZipEntry:也就是代表zip压缩文件条目对象
*/
ZipFile zipFile=null;
try {
//将File对象转化为ZipFile对象
zipFile = new ZipFile(sourceFile);
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while(entries.hasMoreElements()) {
ZipEntry zipEntry = entries.nextElement();
System.out.println("解压:"+zipEntry.getName());
//如果是文件夹 就创建一个文件夹
if(zipEntry.isDirectory()) {
//zipEntry是文件夹
String dirPath=targetFile+"/"+zipEntry.getName();
File dir = new File(dirPath);
dir.mkdirs();
}else {
//zipEntry是文件
File target = new File(targetFile+"/"+zipEntry.getName());
//验证该文件的父文件夹是否存在
if(!target.getParentFile().exists()) {
target.getParentFile().mkdirs();
}
target.createNewFile();
//将压缩文件的内容通过流写入到该文件夹中
InputStream is = zipFile.getInputStream(zipEntry);
FileOutputStream fOS = new FileOutputStream(target);
int len;
byte[] buf=new byte[1024];
while((len=is.read(buf))!=-1) {
fOS.write(buf, 0, len);
}
//释放资源 先开后关 后开先关
fOS.close();
is.close();
}
}
} catch (Exception e) {
throw new RuntimeException("解压出现异常");
}finally {
if(zipFile!=null) {
try {
zipFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}