用ant解压包含中文文件名的压缩文件 中文问题是java中的普遍性问题.今天下午遇到一个包含中文文件名的压缩文件解压问题.找了不少资料.现贴出解集.在java.util.zip包也可以用来处理解压问题,不过对含有中文文件名的压缩包无能为力,这是因为ZipOutputStream压缩和解压ZIP文件对文件名都是以UTF-8编码方式来处理的,而我们用winzip压缩文件对文件名只会以ASCII编码方式来处理.所以会出现编码不一致的问题.有两种解决方案:第一种就是修改ZipOutputStream,参考修改如下:(这个我没有测试过)// ZipEntry e = createZipEntry(getUTF8String(b, 0, len));ZipEntry e=null;try { if (this.encoding.toUpperCase().equals("UTF-8")) e=createZipEntry(getUTF8String(b, 0, len)); else e=createZipEntry(new String(b,0,len,this.encoding));}catch(Exception byteE) { e=createZipEntry(getUTF8String(b, 0, len));}再加一个public ZipInputStream(InputStream in,String encoding) { super(new PushbackInputStream(in,512),new Inflater(true),512); usesDefaultInflater = true; if(in == null) { throw new NullPointerException("in is null"); } this.encoding=encoding;} 第二种方法就是用ant包,可以在官方网站http://ant.apache.org/bindownload.cgi下载,把ant.jar导入到类中.参考用例如下:public void unzip(String zipFileName,String outputDirectory) throws Exception{try { org.apache.tools.zip.ZipFile zipFile = new org.apache.tools.zip.ZipFile(zipFileName); java.util.Enumeration e = zipFile.getEntries(); org.apache.tools.zip.ZipEntry zipEntry = null; while (e.hasMoreElements()){ zipEntry = (org.apache.tools.zip.ZipEntry)e.nextElement(); System.out.println("unziping "+zipEntry.getName()); if (zipEntry.isDirectory()){ String name=zipEntry.getName(); name=name.substring(0,name.length()-1); System.out.println("输出路径:"+outputDirectory+File.separator+name); File f1=new File(outputDirectory+File.separator);f1.mkdir(); File f=new File(outputDirectory+File.separator+name); f.mkdir(); System.out.println("创建目录:"+outputDirectory+File.separator+name); }else{ File f=new File(outputDirectory+File.separator+zipEntry.getName()); f.createNewFile(); InputStream in = zipFile.getInputStream(zipEntry); FileOutputStream out=new FileOutputStream(f); //--------解决了图片失真的情况 int c; byte[] by=new byte[1024]; while((c=in.read(by)) != -1){ out.write(by,0,c); } out.close(); in.close(); } }}catch (Exception ex){}} |