posts - 22,comments - 35,trackbacks - 0

用java.util.zip制作zip压缩文件时,如果制作的压缩文件有中文文件名或中文目录,用WinZip、WinRar解压时会有乱码, 同样,用java.util.zip解压WinZip、WinRar打包的压缩文件时,中文也是乱码,主要原因是因为java.util.zip使用编码和WinZip和WinRar使用的不同,在网上找了半天,发现只有两种解决方法:
1、修改import java.util.zip.ZipInputStream和ZipOutputStream。
2、使用Apache Ant里提供的zip工具。
-------------------------------------
已找到解决方法,就是用Ant的zip来实现,Ant里面可以指定编码,而java.util.zip是写死了的,只能用UTF-8,呵呵
-------------------------------
不要使用java.util.zip的包,用ant.jar放到classpath中

 

 1 // 在classpath中引入ant.jar的包
 2 import  java.io. * ;  
 3 import  java.util. * ;
 4 import  java.io.File;
 5 import  org.apache.tools.zip. * ;
 6
 7 public    class   CDGGzip  
 8 {  
 9    // boolean  packFrame  =  false;  
10    private  File srcPath  = new  File( " d: " + File.separator + " 张任全 " );
11    private  String outFilename = new  String( " d: " + File.separator + " 张任全.zip " );
12 private   int  len = srcPath.listFiles().length;
13 private  String[] filenames  =   new  String[len];
14 public   void  setSrcPath(String src) {
15    srcPath = new  File(src);
16   }

17    public  File getSrcPath() {
18    return  srcPath;
19   }

20 public   void  setOutFilename(String out) {
21    outFilename = out;
22   }

23    public  String getOutFilename() {
24    return  outFilename;
25   }
  
26
27    public   void  gzip() {
28 byte [] buf  =   new   byte [ 1024 ];
29    try   {
30   File[]  files   =   srcPath.listFiles(); 
31    for ( int   i = 0 ;i < len;i ++ )
32    {
33    // if(!files[i].isDirectory())
34 filenames[i] = srcPath.getPath() + File.separator + files[i].getName();
35 }

36   ZipOutputStream out  =   new  ZipOutputStream( new  FileOutputStream(outFilename));
37    for  ( int  i = 0 ; i < filenames.length; i ++
38    {
39   FileInputStream in  =   new  FileInputStream(filenames[i]);
40   out.putNextEntry( new  org.apache.tools.zip.ZipEntry(files[i].getName()));
41    int  len;
42    while  ((len  =  in.read(buf))  >   0
43    {
44   out.write(buf,  0 , len);
45   }

46
47   out.closeEntry();
48   in.close();
49       }

50
51       out.close();
52     }
 
53      catch  (IOException e) 
54      {
55     System.out.println(e); 
56     }

57   }

58   
59    public   static   void  main(String arg[]) {
60   CDGGzip cdggzip = new  CDGGzip();
61   cdggzip.gzip();
62   }

63 }

64
65

posted on 2006-04-21 18:24 kelven 阅读(372) 评论(0)  编辑  收藏 所属分类: java

只有注册用户登录后才能发表评论。


网站导航: