内容简介
本文主要介绍使用ZipFile来提取zip压缩文件中特定后缀(如:png,jpg)的文件并保存到指定目录下。
导入包:import java.util.zip.ZipFile;
如需添加对rar压缩格式的支持,请参考我的另一篇文章:https://www.cnblogs.com/codecat/p/11078485.html
实现代码(仅供参考,请根据实现情况来修改)
/**
* 将压缩文件中指定后缀名称的文件解压到指定目录
* @param compressFile 压缩文件
* @param baseDirectory 解压到的基础目录(在此目录下创建UUID的目录,存入解压的文件)
* @param decompressSuffs 要提取文件的后缀名
* @return
*/
@Override
public void decompressToUUIDDirectory(File compressFile, String baseDirectory, List<String> decompressSuffs) throws Exception {
List<AttachFile> attachFileList = new ArrayList<>(); //验证压缩文件
boolean isFile = compressFile.isFile();
if (!isFile){
System.out.println(String.format("compressFile非文件格式!",compressFile.getName()));
return null;
}
String compressFileSuff = FileUtil.getFileSuffix(compressFile.getName()).toLowerCase();
if (!compressFileSuff.equals("zip")){
System.out.println(String.format("[%s]文件非zip类型的压缩文件!",compressFile.getName()));
return null;
} //region 解压缩文件(zip)
ZipFile zip = new ZipFile(new File(compressFile.getAbsolutePath()), Charset.forName("GBK"));//解决中文文件夹乱码
for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements();){
ZipEntry entry = entries.nextElement();
String zipEntryName = entry.getName();
//过滤非指定后缀文件
String suff = FileUtil.getFileSuffix(zipEntryName).toLowerCase();
if (decompressSuffs != null && decompressSuffs.size() > 0){
if (decompressSuffs.stream().filter(s->s.equals(suff)).collect(Collectors.toList()).size() <= 0){
continue;
}
}
//创建解压目录(如果复制的代码,这里会报错,没有StrUtil,这里就是创建了一个目录来存储提取的文件,你可以换其他方式来创建目录)
String groupId = StrUtil.getUUID();
File group = new File(baseDirectory + groupId);
if(!group.exists()){
group.mkdirs();
}
//解压文件到目录
String outPath = (baseDirectory + groupId + File.separator + zipEntryName).replaceAll("\\*", "/");
InputStream in = zip.getInputStream(entry);
FileOutputStream out = new FileOutputStream(outPath);
byte[] buf1 = new byte[1024];
int len;
while ((len = in.read(buf1)) > 0) {
out.write(buf1, 0, len);
}
in.close();
out.close();
}
//endregion
}
ZipFile