解决Java原生压缩组件不支持中文文件名乱码的问题
最近发现Java原生的Zip压缩组件在压缩过程中,不支持文件名的中文编码,会在压缩过程中把中文文件名变成乱码。Apache的ant包中的压缩组件修复了这个问题,如果你在使用压缩功能时需要支持中文文件名,建议你直接使用Apache的压缩组件来实现这个功能。
具体使用方法:
1.在你的pom文件中增加对Apache的ant工具包的dependency:
org.apache.ant ant 1.9.3
并在头部引用用到的类:
importorg.apache.tools.zip.ZipEntry; importorg.apache.tools.zip.ZipFile; importorg.apache.tools.zip.ZipOutputStream;
2.压缩的方法实现,大家注意,本组件支持设置编码(setEncoding("GBK")方法),解决了中文编码的问题:
publicstaticvoidcompress(StringsrcPath,StringdstPath)throwsIOException{
FilesrcFile=newFile(srcPath);
FiledstFile=newFile(dstPath);
if(!srcFile.exists()){
thrownewFileNotFoundException(srcPath+"doesnotexists");
}
FileOutputStreamout=null;
ZipOutputStreamzipOut=null;
try{
out=newFileOutputStream(dstFile);
zipOut=newZipOutputStream(newBufferedOutputStream(out));
zipOut.setEncoding("GBK");
StringbaseDir="";
compress(srcFile,zipOut,baseDir);
}
catch(Throwableex){
thrownewRuntimeException(ex);
}
finally{
if(null!=zipOut){
zipOut.close();
out=null;
}
if(null!=out){
out.close();
}
}
}
privatestaticvoidcompress(Filefile,ZipOutputStreamzipOut,StringbaseDir)throwsIOException{
if(file.isDirectory()){
compressDirectory(file,zipOut,baseDir);
}else{
compressFile(file,zipOut,baseDir);
}
}
/**压缩一个目录*/
privatestaticvoidcompressDirectory(Filedir,ZipOutputStreamzipOut,StringbaseDir)throwsIOException{
File[]files=dir.listFiles();
for(inti=0;i
3.解压缩的实现:
publicstaticvoiddecompress(StringzipFile,StringdstPath)throwsIOException{
FilepathFile=newFile(dstPath);
if(!pathFile.exists()){
pathFile.mkdirs();
}
ZipFilezip=newZipFile(zipFile);
for(Enumerationentries=zip.getEntries();entries.hasMoreElements();){
ZipEntryentry=(ZipEntry)entries.nextElement();
StringzipEntryName=entry.getName();
InputStreamin=null;
OutputStreamout=null;
try{
in=zip.getInputStream(entry);
StringoutPath=(dstPath+"/"+zipEntryName).replaceAll("\\*","/");;
//判断路径是否存在,不存在则创建文件路径
Filefile=newFile(outPath.substring(0,outPath.lastIndexOf('/')));
if(!file.exists()){
file.mkdirs();
}
//判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
if(newFile(outPath).isDirectory()){
continue;
}
out=newFileOutputStream(outPath);
byte[]buf1=newbyte[1024];
intlen;
while((len=in.read(buf1))>0){
out.write(buf1,0,len);
}
}
finally{
if(null!=in){
in.close();
}
if(null!=out){
out.close();
}
}
}
}
以上代码经过测试,可以直接使用。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。