package com.lxzn.framework.utils;
|
|
import net.lingala.zip4j.core.ZipFile;
|
import net.lingala.zip4j.io.ZipInputStream;
|
import net.lingala.zip4j.model.FileHeader;
|
|
import java.io.File;
|
import java.util.HashMap;
|
import java.util.List;
|
import java.util.Map;
|
|
/**
|
* @Description:
|
* @Author: zhangherong
|
* @Date: Created in 2021/1/29 15:24
|
* @Version: 1.0
|
* @Modified By:
|
*/
|
public class ZipUtil {
|
|
|
/**
|
* 读取压缩文件下的所有文件的文件流
|
* @param file
|
* @return
|
* @throws Exception
|
*/
|
public static Map<String, ZipInputStream> readZipFileStream(File file) throws Exception {
|
ZipFile zipFile = new ZipFile(file);
|
zipFile.setFileNameCharset(getEncoding(file));
|
if(!zipFile.isValidZipFile())
|
return null;
|
List<FileHeader> list = zipFile.getFileHeaders();
|
if(list == null || list.isEmpty())
|
return null;
|
Map<String, ZipInputStream> map = new HashMap<>();
|
for(FileHeader fileHeader : list) {
|
if(!fileHeader.isDirectory()) {
|
ZipInputStream zis = zipFile.getInputStream(fileHeader);
|
String fileName = fileHeader.getFileName();
|
int index = fileName.lastIndexOf("/");
|
if(index == -1) {
|
index = fileName.lastIndexOf("\\\\");
|
if(index == -1) {
|
index = fileName.lastIndexOf("\\");
|
}
|
}
|
if(index != -1) {
|
fileName = fileName.substring(index + 1);
|
}
|
map.put(fileName, zis);
|
}
|
}
|
return map;
|
}
|
|
/**
|
* 判断该使用哪种编码方式解压
|
* @param path
|
* @return
|
* @throws Exception
|
*/
|
private static String getEncoding(File path) throws Exception {
|
String encoding = "GBK";
|
ZipFile zipFile = new ZipFile(path);
|
zipFile.setFileNameCharset(encoding);
|
List<FileHeader> list = zipFile.getFileHeaders();
|
for (int i = 0; i < list.size(); i++) {
|
FileHeader fileHeader = list.get(i);
|
String fileName = fileHeader.getFileName();
|
if (isMessyCode(fileName)) {
|
encoding = "UTF-8";
|
break;
|
}
|
}
|
return encoding;
|
}
|
|
private static boolean isMessyCode(String str) {
|
for (int i = 0; i < str.length(); i++) {
|
char c = str.charAt(i);
|
// 当从Unicode编码向某个字符集转换时,如果在该字符集中没有对应的编码,则得到0x3f(即问号字符?)
|
// 从其他字符集向Unicode编码转换时,如果这个二进制数在该字符集中没有标识任何的字符,则得到的结果是0xfffd
|
if ((int) c == 0xfffd) {
|
// 存在乱码
|
return true;
|
}
|
}
|
return false;
|
}
|
|
public static void main(String[] args) throws Exception {
|
String f = "D://中国.zip";
|
File file = new File(f);
|
Map<String, ZipInputStream> map = readZipFileStream(file);
|
if(map != null && !map.isEmpty()){
|
System.out.println(map.size());
|
for(Map.Entry<String, ZipInputStream> entry : map.entrySet()) {
|
System.out.println(entry.getKey());
|
//entry.getValue().close();
|
}
|
}
|
}
|
}
|