package decompress;     

    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; public class DeCompressUtil {
/**
* 解压zip格式压缩包
* 对应的是ant.jar
*/
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格式压缩包。
* 对应的是java-unrar-0.3.jar,但是java-unrar-0.3.jar又会用到commons-logging-1.1.1.jar
*/
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 = "";
//非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();}
}
}
}
/**
* 解压缩
*/
public static void deCompress(String sourceFile,String destDir) throws Exception{
//保证文件夹路径最后是"/"或者"\"
char lastChar = destDir.charAt(destDir.length()-1);
if(lastChar!='/'&&lastChar!='\\'){
destDir += File.separator;
}
//根据类型,进行相应的解压缩
String type = sourceFile.substring(sourceFile.lastIndexOf(".")+1);
if(type.equals("zip")){
DeCompressUtil.unzip(sourceFile, destDir);
}else if(type.equals("rar")){
DeCompressUtil.unrar(sourceFile, destDir);
}else{
throw new Exception("只支持zip和rar格式的压缩包!");
}
}
}

RAR压缩算法是不公开的,所以这方面的开源项目不多

幸好有一个叫unrar的开源项目支持RAR的解压,但不能压缩RAR文件

不过,直接使用unrar却不能支持带密码的RAR文件解压,经过多方查找,终于在Google Code上面找到一个支持密码的unrar版本,下载地址:http://code.google.com/p/java-unrar/

该项目依赖Jar包:

commons-logging.jar  比较常用,可以到Apache官网下载

gnu-crypto.jar  可以在http://www.gnu.org/software/gnu-crypto/下载

下面是一个简单的解压示例:

package com.reyo.demo.rar;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.apache.commons.io.IOUtils;

import de.innosystec.unrar.Archive;
import de.innosystec.unrar.exception.RarException;
import de.innosystec.unrar.rarfile.FileHeader;

/**
 * RAR格式压缩文件解压工具类
 * 不支持RAR格式压缩
 * 支持中文,支持RAR压缩文件密码
 * 依赖jar包
 * commons-io.jar
 * commons-logging.jar
 * java-unrar-decryption-supported.jar
 * gnu-crypto.jar
 *
 * @author ninemax
 */
public class RarDecompressionUtil {
 
 public static final String SEPARATOR = File.separator;
 
 // =============================== RAR Format ================================
 /**
  * 解压指定RAR文件到当前文件夹
  * @param srcRar 指定解压
  *  @param password 压缩文件时设定的密码
  * @throws IOException
  */
 public static void unrar(String srcRar, String password) throws IOException {
  unrar(srcRar, null, password);
 }
 
 /**
  * 解压指定的RAR压缩文件到指定的目录中
  * @param srcRar 指定的RAR压缩文件
  * @param destPath 指定解压到的目录
  *  @param password 压缩文件时设定的密码
  * @throws IOException
  */
 public static void unrar(String srcRar, String destPath, String password) throws IOException {
  File srcFile = new File(srcRar);
  if (!srcFile.exists()) {
   return;
  }
  if (null == destPath || destPath.length() == 0) {
   unrar(srcFile, srcFile.getParent(), password);
   return;
  }
  unrar(srcFile,destPath, password);
 }
 
 /**
  * 解压指定RAR文件到当前文件夹
  * @param srcRarFile 解压文件
  *  @param password 压缩文件时设定的密码
  * @throws IOException
  */
 public static void unrar(File srcRarFile, String password) throws IOException {
  if (null == srcRarFile || !srcRarFile.exists()) {
   throw new IOException("指定文件不存在.");
  }
  unrar(srcRarFile, srcRarFile.getParent(),password);
 }
 
 /**
  * 解压指定RAR文件到指定的路径
  * @param srcRarFile 需要解压RAR文件
  * @param destPath 指定解压路径
  * @param password 压缩文件时设定的密码
  * @throws IOException
  */
 public static void unrar(File srcRarFile, String destPath, String password) throws IOException {
  if (null == srcRarFile || !srcRarFile.exists()) {
   throw new IOException("指定压缩文件不存在.");
  }
  if (!destPath.endsWith(SEPARATOR)) {
   destPath += SEPARATOR;
  }
  Archive archive = null;
  OutputStream unOut = null;
  try {
   archive = new Archive(srcRarFile, password, false);
   FileHeader fileHeader = archive.nextFileHeader();
   while(null != fileHeader) {
    if (!fileHeader.isDirectory()) {
     // 1 根据不同的操作系统拿到相应的 destDirName 和 destFileName
     String destFileName = "";
     String destDirName = "";
     if (SEPARATOR.equals("/")) {  // 非windows系统
      destFileName = (destPath + fileHeader.getFileNameW()).replaceAll("\\\\", "/");
      destDirName = destFileName.substring(0, destFileName.lastIndexOf("/"));
     } else {  // windows系统
      destFileName = (destPath + fileHeader.getFileNameW()).replaceAll("/", "\\\\");
      destDirName = destFileName.substring(0, destFileName.lastIndexOf("\\"));
     }
     // 2创建文件夹
     File dir = new File(destDirName);
     if (!dir.exists() || !dir.isDirectory()) {
      dir.mkdirs();
     }
     // 抽取压缩文件
     unOut = new FileOutputStream(new File(destFileName));
     archive.extractFile(fileHeader, unOut);
     unOut.flush();
     unOut.close();
    }
    fileHeader = archive.nextFileHeader();
   }
   archive.close();
  } catch (RarException e) {
   e.printStackTrace();
  } finally {
   IOUtils.closeQuietly(unOut);
  }
 }
}

java解压缩zip和rar的工具类的更多相关文章

  1. Java判断不为空的工具类总结

    1.Java判断是否为空的工具类,可以直接使用.包含,String字符串,数组,集合等等. package com.bie.util; import java.util.Collection; imp ...

  2. Java字符串转16 进制工具类Hex.java

    Java字符串转16 进制工具类Hex.java 学习了:https://blog.csdn.net/jia635/article/details/56678086 package com.strin ...

  3. Java中的AES加解密工具类:AESUtils

    本人手写已测试,大家可以参考使用 package com.mirana.frame.utils.encrypt; import com.mirana.frame.constants.SysConsta ...

  4. java里poi操作excel的工具类(兼容各版本)

    转: java里poi操作excel的工具类(兼容各版本) 下面是文件内具体内容,文件下载: import java.io.FileNotFoundException; import java.io. ...

  5. java.util.Arrays----操作数组的工具类

    java.util.Arrays操作数组的工具类,里面定义了很多操作数组的方法 1.boolean equals(int[] a,int[] b):判断两个数组是否相等. 2.String toStr ...

  6. java将文件打包成ZIP压缩文件的工具类实例

    package com.lanp; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import ja ...

  7. java中自己常用到的工具类-压缩解压zip文件

    package com.ricoh.rapp.ezcx.admintoolweb.util; import java.io.File; import java.io.FileInputStream; ...

  8. java解压缩zip

    依赖的包: <!-- https://mvnrepository.com/artifact/org.apache.ant/ant --> <dependency> <gr ...

  9. Zip包解压工具类

    最近在做项目的自动检测离线升级,使用到了解压zip包的操作,本着拿来主义精神,搞了个工具类(同事那边拿的),用着还不错. package com.winning.polaris.admin.utils ...

随机推荐

  1. inline-block元素间隙问题原因及解决方法

    inline-block元素间隙问题原因及解决方法 原因: 书写时由空格.换行或回车所产生空白符所致 解决方法: 方法1:font-size:0 方法2:改变书写方式 方法3:使用margin负值 方 ...

  2. watch案例解析(element-ui el-select 无法选中问题剖析)

    fire 读在最前面: 1.此文章衔接Vue 虚拟Dom 及 部分生命周期初探,相关整体知识点请先阅读后再继续本文阅读 问:子组件中明明有watch value,为什么this.$emit('inpu ...

  3. ASP.Net1

    一.Web应用程序与传统桌面应用程序的不同: 1.产品级的Web应用程序总是包括至少两台联网的机器:一台承载网站,另一台在Web浏览器中查看数据. 即:我们通过自己的电脑浏览Web程序,这个程序会向服 ...

  4. G 最短路

    题目描述三国时期,南蛮王孟获叛乱,诸葛亮起兵平乱.当深入南蛮之地时,遇当地人绘得地图,发现各地分别由各个寨主据守,若诸葛亮想兵分多路进军,尽快占领各个山寨(必须占领所有山寨),并且最终所有士兵都汇聚到 ...

  5. PHP 操作redis 封装的类 转的

    <?php/** * Redis 操作,支持 Master/Slave 的负载集群 * * @author jackluo */class RedisCluster{           // ...

  6. 为什么因式分解n=pq分别得到pq是求解密钥中d的关键

    从d的来源来说,它是这样来的: "找到一个数d,使得ed-1能够被z整除.即给定e,选择数d,使得ed被z除的余数为1",即  ed=1 (mod z) 上面这句话中,为了求d,我 ...

  7. Action的模型绑定

    - 你真的会用Action的模型绑定吗?   在QQ群或者一些程序的交流平台,经常会有人问:我怎么传一个数组在Action中接收.我传的数组为什么Action的model中接收不到.或者我在ajax的 ...

  8. H5的简介

    1.H5的诞生 2.介绍 HTML5 将成为 HTML.XHTML 以及 HTML DOM 的新标准. HTML5 是 W3C 与 WHATWG 合作的结果. WHATWG 致力于 web 表单和应用 ...

  9. python 实现远端ftp文件上传下载

    python 实现ftp上传下载 * 脚本需要传入两个参数,参数1为需要从远端ftp站点下载文件名称,参数2为已知需要下载的文件md5值,文件下载完成后会自动进行md5值校验 * 运行示例 [root ...

  10. MySQL Binlog 介绍

    Binlog 简介 MySQL中一般有以下几种日志: 日志类型 写入日志的信息 错误日志 记录在启动,运行或停止mysqld时遇到的问题 通用查询日志 记录建立的客户端连接和执行的语句 二进制日志 记 ...