直接上工具类:

package com.ksource.pwlp.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile; import com.github.junrar.Archive;
import com.github.junrar.rarfile.FileHeader; public class ZipAndRarUnpackUtil { /**
* 解压zip
*
* @param zipFile
* @param descDir
* @throws Exception
*/
public void unZipFiles(File zipFile, String descDir) throws Exception {
System.out.println("******************解压开始********************");
File pathFile = new File(descDir);
if (!pathFile.exists()) {
pathFile.mkdirs();
}
ZipFile zip = new ZipFile(zipFile,Charset.forName("GBK"));
for (Enumeration entries = zip.entries(); entries.hasMoreElements();) {
ZipEntry entry = (ZipEntry) entries.nextElement();
String zipEntryName = entry.getName();
InputStream in = zip.getInputStream(entry);
String outPath = (descDir + "/" + zipEntryName).replaceAll("\\*", "/");
// 判断路径是否存在,不存在则创建文件路径
File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
if (!file.exists()) {
file.mkdirs();
}
// 判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
if (new File(outPath).isDirectory()) {
continue;
}
OutputStream out = new FileOutputStream(outPath);
byte[] buf1 = new byte[1024];
int len;
while ((len = in.read(buf1)) > 0) {
out.write(buf1, 0, len);
}
if ((zipEntryName.trim().lastIndexOf("/")) == -1) { }
in.close();
out.close();
}
System.out.println("******************解压完毕********************");
} /**
* 解压rar格式压缩包。
* 对应的是java-unrar-0.3.jar,但是java-unrar-0.3.jar又会用到commons-logging-1.1.1.jar
*/
public void unRarFiles(File rarFile, String descDir) throws Exception{
Archive a = null;
FileOutputStream fos = null;
try{
a = new Archive(rarFile);
FileHeader fh = a.nextFileHeader();
while(fh!=null){
if(!fh.isDirectory()){
//1 根据不同的操作系统拿到相应的 destDirName 和 destFileName
//String compressFileName = fh.getFileNameString().trim();
String compressFileName = fh.getFileNameW().trim();
if(!existZH(compressFileName)){
compressFileName = fh.getFileNameString().trim();
}
String destFileName = "";
String destDirName = "";
//非windows系统
if(File.separator.equals("/")){
destFileName = descDir + compressFileName.replaceAll("\\\\", "/");
destDirName = destFileName.substring(0, destFileName.lastIndexOf("/"));
//windows系统
}else{
destFileName = descDir + 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 boolean existZH(String str) {
String regEx = "[\\u4e00-\\u9fa5]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
while (m.find()) {
return true;
}
return false;
} /**
* 文件夹遍历
* @param path
* @throws Exception
*/
public void traverse(String path,String parent_id) throws Exception {
System.out.println("path---->" + path);
File file = new File(path);
Map<String, Object> map = new HashMap<String, Object>();
if (file.exists()) {
File[] files = file.listFiles();
if (files.length == 0) {
System.out.println("文件夹是空的!");
return;
} else {
String k_id = UUID.randomUUID().toString(); for (File file2 : files) {
if (file2.isDirectory()) {//文件夹 traverse(file2.getAbsolutePath(),parent_id);
parent_id = k_id;
} else if (file2.isFile()){//文件 }
}
}
} else {
System.out.println("文件不存在!");
}
} /**
* 采用命令行方式解压文件(rar解压会出现版本不一致造成的解压失败,所以用命令方式解压更稳妥)
* @param zipFile 压缩文件
* @param destDir 解压结果路径
* @param cmdPath WinRAR.exe的路径,也可以在代码中写死
* @return
*/
public void realExtract(File rarFile, String destDir) {
// 解决路径中存在/..格式的路径问题
destDir = new File(destDir).getAbsoluteFile().getAbsolutePath();
while(destDir.contains("..")) {
String[] sepList = destDir.split("\\\\");
destDir = "";
for (int i = 0; i < sepList.length; i++) {
if(!"..".equals(sepList[i]) && i < sepList.length -1 && "..".equals(sepList[i+1])) {
i++;
} else {
destDir += sepList[i] + File.separator;
}
}
}
String path = System.getProperty("user.dir");
boolean bool = false;
if (rarFile.exists()) {
// 开始调用命令行解压,参数-o+是表示覆盖的意思
String cmdPath = path+"\\metadata\\7zip\\7z.exe";
cmdPath = cmdPath .replaceAll(" ", "\" \"");//所有空格都替换成带有双引号的空格
String cmd = cmdPath + " x " + rarFile.getPath() + " -o" + destDir;
System.out.println(cmd);
try {
Process proc = Runtime.getRuntime().exec(cmd);
if (proc.waitFor() != 0) {
if (proc.exitValue() == 0) {
bool = false;
}
} else {
bool = true;
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("解压" + (bool ? "成功" : "失败"));
}
}
}
realExtract方法中的7z压缩包路径cmdPath是先将7z压缩包安装完之后拷贝安装路径到项目中去,然后运用cmd命令执行7z压缩包
7z压缩包下载地址:https://www.7-zip.org/a/7z1900-x64.exe

Zip文件和RAR文件解压的更多相关文章

  1. C# -- 文件的压缩与解压(GZipStream)

    文件的压缩与解压 需引入 System.IO.Compression; 1.C#代码(入门案例) Console.WriteLine("压缩文件..............."); ...

  2. XML序列化 判断是否是手机 字符操作普通帮助类 验证数据帮助类 IO帮助类 c# Lambda操作类封装 C# -- 使用反射(Reflect)获取dll文件中的类型并调用方法 C# -- 文件的压缩与解压(GZipStream)

    XML序列化   #region 序列化 /// <summary> /// XML序列化 /// </summary> /// <param name="ob ...

  3. 通过SharpZipLib实现文件夹压缩以及解压

    代码说明 基于SharpZipLib实现Zip压缩解压,扩展实现文件夹级别压缩解压: 项目源码:MasterChief.DotNet.Infrastructure.Zip Install-Packag ...

  4. Asp.net中文件的压缩与解压

    这里笔者为大家介绍在asp.net中使用文件的压缩与解压.在asp.net中使用压缩给大家带来的好处是显而易见的,首先是减小了服务器端文件存储的空间,其次下载时候下载的是压缩文件想必也会有效果吧,特别 ...

  5. HDFS中文件的压缩与解压

    HDFS中文件的压缩与解压 文件的压缩有两大好处:1.可以减少存储文件所需要的磁盘空间:2.可以加速数据在网络和磁盘上的传输.尤其是在处理大数据时,这两大好处是相当重要的. 下面是一个使用gzip工具 ...

  6. C#调用7z实现文件的压缩与解压

    1.关于7z 首先在这里先介绍一下7z压缩软件,7z是一种主流的 压缩格式,它拥有极高的压缩比.在计算机科学中,7z是一种可以使用多种压缩算法进行数据压缩的档案格式.主要有以下特点: 来源且模块化的组 ...

  7. RAR压缩解压命令

    RAR压缩解压命令 这几天一直没空更新博客,现在补上: 先介绍一下rar的命令格式及相关参数含义(摘自rar): 用法:   rar <命令> -<开关 1> -<开关 ...

  8. 把自解压的RAR压缩包解压到指定的软件安装目录

    原文 把自解压的RAR压缩包解压到指定的软件安装目录 今天千里独行同学给轻狂来信问了一个问题:如何把一个自解压的RAR压缩包解压到我们指定的软件安装目录.   其实,在NSIS中,我们可以灵活运用相关 ...

  9. (转)Unity中使用C#实现Zip包的压缩与解压

    使用SharpZipLib库,下载地址为:http://icsharpcode.github.io/SharpZipLib/ /************************************ ...

随机推荐

  1. 2018牛客网暑假ACM多校训练赛(第六场)I Team Rocket 线段树

    原文链接https://www.cnblogs.com/zhouzhendong/p/NowCoder-2018-Summer-Round6-I.html 题目传送门 - https://www.no ...

  2. Selenium3详解(基本操作,定位方法)

    如果想使用selenium驱动不同的浏览器,必须单独下载并设置不同的浏览器驱动. 基本操作: 刷新:refresh, 获取浏览器窗口大小:get_window_size 设置浏览器窗口大小:set_w ...

  3. Zookeeper三个监听案例

    一.监听某一节点内容 /** * @author: PrincessHug * @date: 2019/2/25, 14:28 * @Blog: https://www.cnblogs.com/Hel ...

  4. ELM:ELM实现鸢尾花种类测试集预测识别正确率(better)结果对比—Jason niu

    load iris_data.mat P_train = []; T_train = []; P_test = []; T_test = []; for i = 1:3 temp_input = fe ...

  5. poj 1966(求点连通度,边连通度的一类方法)

    题目链接:http://poj.org/problem?id=1966 思路:从网上找了一下大牛对于这类问题的总结:图的连通度问题是指:在图中删去部分元素(点或边),使得图中指定的两个点s和t不连通  ...

  6. Ajax技术使用之ajax与模态框结合的妙用

    Ajax技术使用之ajax与模态框结合的妙用 要求: 使用ajax的方式提交数据:https://www.cnblogs.com/-wenli/p/10470063.html 使用模态框完成增加数据, ...

  7. 004.MySQL双主+Keepalived高可用

    一 基础环境 主机名 系统版本 MySQL版本 主机IP Master01 CentOS 6.8 MySQL 5.6 172.24.8.10 Master02 CentOS 6.8 MySQL 5.6 ...

  8. python 词云小demo

    词云小demo jiebawordcloud 一 什么是词云? 由词汇组成类似云的彩色图形.“词云”就是对网络文本中出现频率较高的“关键词”予以视觉上的突出,形成“关键词云层”或“关键词渲染”,从而过 ...

  9. Socket 网络通信

    Socket 网络通信 1.OSI (Open System Interconnect Reference Model)(开放系统互联参考模型) 从下低到高 :物理层.数据链路层.网络层.传输层.会话 ...

  10. BZOJ.1568.[JSOI2008]Blue Mary开公司(李超线段树)

    题目链接 线段树每个节点记录\(f(mid)\)最大的直线(在\(mid\)处函数值最大的直线),称作优势线段(还是直线啊...无所谓了). 如果是在区间插入线段会影响\(O(\log n)\)个区间 ...