package com.cn.teachmobile.utils;import java.io.File;import java.io.FileOutputStream;import org.apache.tools.ant.Project;import org.apache.tools.ant.taskdefs.Expand;import de.innosystec.unrar.Archive;import de.innosystec.unrar.rarfile.FileHeader;/** * @author gongchaobin * * 解压缩zip rar文件 */public class ZipHelper { /** * 解压zip文件 * * @param sourceZip 需要解压的文件路径 * @param destDir 解压存放的路径 * @throws Exception */ private static void unzip(String sourceZip,String destDir) throws Exception{ try{ Project p = new Project(); Expand e = new Expand(); e.setProject(p); e.setSrc(new File(sourceZip)); e.setOverwrite(false); e.setDest(new File(destDir)); /* ant下的zip工具默认压缩编码为UTF-8编码, 而winRAR软件压缩是用的windows默认的GBK或者GB2312编码 所以解压缩时要制定编码格式 */ e.setEncoding("gbk"); e.execute(); }catch(Exception e){ throw e; } } /** * 解压rar文件 * * @param sourceRar * @param destDir * @throws Exception */ private static void unrar(String sourceRar,String destDir) throws Exception{ Archive a = null; FileOutputStream fos = null; try{ a = new Archive(new File(sourceRar)); FileHeader fh = a.nextFileHeader(); while(fh!=null){ if(!fh.isDirectory()){ //1 根据不同的操作系统拿到相应的 destDirName 和 destFileName String compressFileName = fh.getFileNameString().trim(); String destFileName = ""; String destDirName = ""; compressFileName = new String(compressFileName.getBytes("UTF-8"),"GB2312"); //非windows系统 if(File.separator.equals("/")){ destFileName = destDir + compressFileName.replaceAll("\\\\", "/"); destDirName = destFileName.substring(0, destFileName.lastIndexOf("/")); //windows系统 }else{ destFileName = destDir + compressFileName.replaceAll("/", "\\\\"); destDirName = destFileName.substring(0, destFileName.lastIndexOf("\\")); } //2创建文件夹 File dir = new File(destDirName); if(!dir.exists()||!dir.isDirectory()){ dir.mkdirs(); } //3解压缩文件 fos = new FileOutputStream(new File(destFileName)); a.extractFile(fh, fos); fos.close(); fos = null; } fh = a.nextFileHeader(); } a.close(); a = null; }catch(Exception e){ throw e; }finally{ if(fos!=null){ try{fos.close();fos=null;}catch(Exception e){e.printStackTrace();} } if(a!=null){ try{a.close();a=null;}catch(Exception e){e.printStackTrace();} } } } }
三个包的下载链接: