解压zip格式文件,可以解压直接压缩的文件,也可以解压放在一个文件夹中压缩的zip文件
当多个文件放在一个文件夹中压缩的时候,解压的时候有可能没有先解压文件夹,导致其他文件找不到路径而报错, 所以先解压文件夹后再解压文件
filePath:压缩文件的完整路径
zipDir:压缩文件所在文件夹位置
package zip_util;
import java.io.*;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* @author HY
*/
public class ZipUtil {
private static int BUFFER = 1024;
public static void main(String[] args) {
unzip("D:\\test.zip","D:\\");
}
public static String unzip(String filePath,String zipDir) {
String name = "";
try {
BufferedOutputStream dest = null;
BufferedInputStream is = null;
ZipEntry entry;
ZipFile zipfile = new ZipFile(filePath);
Enumeration dir = zipfile.entries();
while (dir.hasMoreElements()){
entry = (ZipEntry) dir.nextElement();
if( entry.isDirectory()){
name = entry.getName();
name = name.substring(0, name.length() - 1);
File fileObject = new File(zipDir + name);
fileObject.mkdir();
}
}
Enumeration e = zipfile.entries();
while (e.hasMoreElements()) {
entry = (ZipEntry) e.nextElement();
if( entry.isDirectory()){
continue;
}else{
is = new BufferedInputStream(zipfile.getInputStream(entry));
int count;
byte[] dataByte = new byte[BUFFER];
FileOutputStream fos = new FileOutputStream(zipDir+entry.getName());
dest = new BufferedOutputStream(fos, BUFFER);
while ((count = is.read(dataByte, 0, BUFFER)) != -1) {
dest.write(dataByte, 0, count);
}
dest.flush();
dest.close();
is.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return name;
}
}