读取压缩文件
1、背景
D盘下面有一个zipTest1.zip压缩文件
1.1 zipTest里面的内容
1.2 zipTest中有三个文件夹dir1、dir2、dir3
1.3 每一个文件夹下都有一个.txt文件
2、要求
读取D盘下面zipTest1.zip压缩文件里的内容到D盘下面zipTest2
3、实现
public static void main(String[] args) {
String filePath = "D:/zipTest1.zip";
FileUtils.setFileSavePath("D:/zipTest2");
Map<String,Map<String,File>> map = readZipFile(filePath);
for(Map.Entry<String, Map<String, File>> dirNameEntry : map.entrySet()){
String dirName = dirNameEntry.getKey();
for(Map.Entry<String,File> fileEntry : dirNameEntry.getValue().entrySet()){
String[] nameArray = fileEntry.getKey().split("\\" + StrConstant.DOT);
String fileName = nameArray[0];
String suffix = nameArray[1];
MultipartFile multipartFile = FileUtils.file2MultipartFile(fileEntry.getValue(), fileName, StrConstant.DOT + suffix);
FileUtils.upload2local(multipartFile,dirName,null,FilePixModeEnum.NONE,Boolean.FALSE);
}
}
}
/**
* @author: yc
* @des: 读取压缩文件
* @date: 2024/08/06 15:00
*/
public static Map<String,Map<String,File>> readZipFile(String filePath){
Map<String,Map<String,File>> map = new LinkedHashMap<>();
if(StringUtils.isBlank(filePath)){
return map;
}
try {
ZipFile zipFile = new ZipFile(filePath, Charset.forName("GBK"));
// 获取所有文件夹名称
List<String> directoryNameList = zipFile.stream().filter(i -> i.isDirectory()).map(i -> i.getName()).collect(Collectors.toList());
// 找出顶级目录名称
String topDirName = directoryNameList.stream().filter(i -> i.split(StrConstant.SLASH).length == 1).collect(Collectors.toList()).get(0);
directoryNameList.remove(topDirName);
for(String directoryName : directoryNameList){
// 文件夹下的文件
Map<String,File> fileMap = new LinkedHashMap<>();
List<? extends ZipEntry> zipEntryList = zipFile.stream()
.filter(i -> !i.isDirectory())
.filter(i -> i.getName().startsWith(directoryName))
.collect(Collectors.toList());
for(ZipEntry zipEntry : zipEntryList){
String path = zipEntry.getName();
String[] array = path.split(StrConstant.SLASH);
String name = array[array.length - 1];
String[] nameArray = name.split("\\" + StrConstant.DOT);
String fileName = nameArray[0];
String suffix = nameArray[1];
InputStream inputStream = zipFile.getInputStream(zipEntry);
File file = File.createTempFile(fileName,suffix);
FileOutputStream fileOutputStream = new FileOutputStream(file);
FileUtils.inputStream2outputStream(inputStream,fileOutputStream);
fileMap.put(name,file);
file.deleteOnExit();
}
map.put(directoryName.replace(topDirName,StrConstant.EMPTY_STR).replace(StrConstant.SLASH,StrConstant.EMPTY_STR),fileMap);
}
}catch (Exception e){
System.out.println(e.getMessage());
}
return map;
}
4、StrConstant
StrConstant
5、FileUtils
FileUtils