您的位置:首页 > 编程语言 > Java开发

java解压zip文件至指定文件夹

2018-09-09 15:17 721 查看
前面,笔者讲到。如何把文件打包为zip包,那么反过来怎么把zip文件包解压为正常文件呢?把zip包解压为正常文件包,要比把文件打包为zip简单一点。因为存在多级文件的压缩,却不存在多级文件的解压缩。也就是说,压缩时,你要把所有文件都塞到压缩包里。而解压缩只需要解压一级,压缩包里面的压缩文件则不必理会。
直接上代码喽:

/**
* 解压文件
* @param zipPath 要解压的目标文件
* @param descDir 指定解压目录
* @return 解压结果:成功,失败
*/
@SuppressWarnings("rawtypes")
public boolean decompressZip(String zipPath, String descDir) {
File zipFile = new File(zipPath);
boolean flag = false;
File pathFile = new File(descDir);
if(!pathFile.exists()){
pathFile.mkdirs();
}
ZipFile zip = null;
try {
zip = new ZipFile(zipFile, Charset.forName("gbk"));//防止中文目录,乱码
for(Enumeration entries = zip.entries(); entries.hasMoreElements();){
ZipEntry entry = (ZipEntry)entries.nextElement();
String zipEntryName = entry.getName();
InputStream in = zip.getInputStream(entry);
//指定解压后的文件夹+当前zip文件的名称
String outPath = (descDir+zipEntryName).replace("/", File.separator);
//判断路径是否存在,不存在则创建文件路径
File file = new File(outPath.substring(0, outPath.lastIndexOf(File.separator)));
if(!file.exists()){
file.mkdirs();
}
//判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
if(new File(outPath).isDirectory()){
continue;
}
//保存文件路径信息(可利用md5.zip名称的唯一性,来判断是否已经解压)
System.err.println("当前zip解压之后的路径为:" + outPath);
OutputStream out = new FileOutputStream(outPath);
byte[] buf1 = new byte[2048];
int len;
while((len=in.read(buf1))>0){
out.write(buf1,0,len);
}
in.close();
out.close();
}
flag = true;
//必须关闭,要不然这个zip文件一直被占用着,要删删不掉,改名也不可以,移动也不行,整多了,系统还崩了。
zip.close();
} catch (IOException e) {
e.printStackTrace();
}
return flag;
}

找个例子实现一下:
就你了!



调用:

String deal_zip = "C:\\20180909.zip";
String agter_zip = "D:\\red_ant_file";//解压完塞到这里吧
boolean is_success = AllServiceIsHere.decompressZip(deal_zip, agter_zip);
if(is_success) {
System.err.println("恭喜你,解压成功!");
}else {
System.err.println("sorry, you failed!");
}

走你!



嗯嗯,达到了我所要求的。赶集去喽!





内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  解压 zip 文件