最近项目需要解析接口过来的日志文件,日志文件采用zip打包方式传递过来,zip包的内的文件名包含中文。
刚开始采用的java.util下的zip包进行解压,发现路径中文乱码,代码如下:
/**
* 解压文件到指定目录
*
* @param zipFile zip文件
* @param descDir 输出目录
* @author lee
*/
@SuppressWarnings("rawtypes")
public static void unZipFiles(File zipFile, String descDir)
throws IOException {
File pathFile = new File(descDir);
if (!pathFile.exists()) {
pathFile.mkdirs();
}
ZipFile zip = new ZipFile(zipFile);
for (Enumeration entries = zip.entries(); entries.hasMoreElements();) {
ZipEntry entry = (ZipEntry) entries.nextElement();
String zipEntryName = entry.getName();
InputStream in = zip.getInputStream(entry);
String outPath = (descDir + zipEntryName).replaceAll("\\*", "/");
;
// 判断路径是否存在,不存在则创建文件路径
File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
if (!file.exists()) {
file.mkdirs();
}
// 判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
if (new File(outPath).isDirectory()) {
continue;
}
// 输出文件路径信息
System.out.println(outPath);
OutputStream 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();
}
zip.close();
}
在网上查阅相关资料,java.uil下的zip处理类不包含中文名字的兼容,需要采用ant包下的apache.tools工具进行解析,代码如下:
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.xml.sax.SAXException;
import java.io.*;
import java.util.*;
public class ZipUtils {
/**
* 解析附件zip包
* @param unZipFileName 解压的zip文件
* @param outputDirectory 输出目录
* @throws StrategyException
*/
public static void unZip(String unZipFileName,String outputDirectory) throws StrategyException {
FileOutputStream fileOut = null;
InputStream inputStream = null;
ZipFile zipFile = null;
int readedBytes;
try{
//创建输出目录
File outputDirFile = new File(outputDirectory);
if(!outputDirFile.exists()){
outputDirFile.mkdir();
}
if(System.getProperty("os.name").toLowerCase().indexOf("windows") >= 0){
zipFile = new ZipFile(unZipFileName,"GBK");
}else if(System.getProperty("os.name").toLowerCase().indexOf("linux") >= 0){
zipFile = new ZipFile(unZipFileName,"UTF-8");
}
for(Enumeration entries = zipFile.getEntries();entries.hasMoreElements();){
ZipEntry entry = (ZipEntry)entries.nextElement();
File f = new File(outputDirectory + File.separator + entry.getName());
f.createNewFile();
inputStream = zipFile.getInputStream(entry);
fileOut = new FileOutputStream(f);
byte[] buf = new byte[1024];
while(( readedBytes = inputStream.read(buf) ) > 0){
fileOut.write(buf , 0 , readedBytes );
}
}
}catch(Exception e){
e.printStackTrace();
throw new StrategyException("解析附件失败,请检查压缩包是否损坏!");
}finally {
IOUtils.closeQuietly(fileOut);
IOUtils.closeQuietly(inputStream);
}
}
}