Java Zip 压缩目录(文件)之中文乱码问题

运行环境

         Jdk 1.5win 7中文版

 

JDK1.5中有zip压缩相关的API,在java.util.zip包下面。正常情况下,使用JDK自带的API把目录(文件)压缩成zip包,步骤如下:

 

ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file));

Out.putNextEntry(new ZipEntry(entryName));

//If entry is directory

//above codes are enough

//else if entry is file

//then the codes below is needed

FileInputStream in = new FileInputStream(infile);

byte[] bs = newbyte[1024];

int b = 0;

while((b = in.read(bs)) != -1) {

zos.write(bs, 0, b);

}

in.close();

 

如果要打包的目录名或文件名中包含中文字符,这些目录或文件的名称就会出现乱码,原因是JDK自带的API中,在写入ZipEntry的时候,采用的编码默认的是UTF8(貌似还只有这一种,没办法更改,据说Java7有所改善),而win7操作系统中文版在处理zip文件的时候采用的是GBK编码,编码和解码的处理不同,造成了打包之后的文件在win7中文版中看到的是乱码。

 

可以采用的解决方案是通过利用第三方API实现zip压缩,以解决中文乱码问题。以下是利用apachecompresszip压缩的实现,所需jar包为commons-compress-1.2.jar,其官方下载地址为http://commons.apache.org/compress/download_compress.cgi

 

ArchiveOutputStream os = new ArchiveStreamFactory()

              .createArchiveOutputStream(ArchiveStreamFactory.ZIP, out);

if(os instanceof ZipArchiveOutputStream) {

((ZipArchiveOutputStream) os).setEncoding("GBK");

}

//...some code omitted

os.putArchiveEntry(new ZipArchiveEntry(path+"/"+file.getName()));

IOUtils.copy(new FileInputStream(file), os);

os.closeArchiveEntry();

posted on 2011-09-27 16:44  shosciation  阅读(6881)  评论(1编辑  收藏  举报