1.使用unzip这个方法进行解压。方法代码如下,其中zipFileName是要解压的文件名,unzipDir是解压后存放的文件位置。这里有两点要注意
(1)zipFileName要是文件的路径,例如文件名为test.zip,存放在F盘的mywork文件夹下,那么这里的zipFileName要为F:\\mywork\test.zip
(2)如果压缩文件夹的内部有多个文件,但是in.getNextEntry()没能全部遍历出来,或者始终遍历为null的时候,要注意看一下是否压缩的文件名称中有中文。一般来说压缩文件夹中的中文文件没有办法通过in.getNextEntry()读到。
以下代码参考:https://blog.csdn.net/xiexingshishu/article/details/46277581
public void unzip(String zipFileName , String unzipDir) throws Exception{
FileInputStream fi = new FileInputStream(zipFileName);
ZipInputStream in = new ZipInputStream(fi);
ZipEntry entry;
while ((entry = in.getNextEntry()) != null) {
String fileName = entry.getName();
//有层级结构,就先创建目录
String tmp;
int index = fileName.lastIndexOf('/');
if (index != -1) {
tmp = fileName.substring(0, index);
tmp = unzipDir + "/" + tmp;
File f = new File(tmp);
f.mkdirs();
}
//创建文件
fileName = unzipDir + "/" + fileName;
File file = new File(fileName);
file.createNewFile();
FileOutputStream out = new FileOutputStream(file);
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
out.close();
}
in.close();
}