java解压.rar、.zip和.7z格式压缩包

news/2024/11/23 0:24:52/
  1. 解压zip格式文件用到的jar包有ant-1.6.5.jar和commons-logging-1.2.jar ,在pom.xml中输入:
<!--zip-->
<dependency><groupId>ant</groupId><artifactId>ant</artifactId><version>1.6.5</version>
</dependency> 
<dependency><groupId>commons-logging</groupId><artifactId>commons-logging</artifactId><version>1.2</version>
</dependency>

解压rar格式文件用到的jar包为java-unrar-0.5.jar
三个jar包存放位置:
https://download.csdn.net/download/small_emotion/10922796
解压7z所需jar包

<!--7z-->
<dependency><groupId>net.sf.sevenzipjbinding</groupId><artifactId>sevenzipjbinding</artifactId><version>9.20-2.00beta</version></dependency><dependency><groupId>net.sf.sevenzipjbinding</groupId><artifactId>sevenzipjbinding-all-platforms</artifactId><version>9.20-2.00beta</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>3.8.1</version><scope>test</scope></dependency>

2.解压代码

package com.nian.energy.util;package com.nian.energy.worksheet.util;import de.innosystec.unrar.Archive;
import de.innosystec.unrar.rarfile.FileHeader;
import net.sf.sevenzipjbinding.*;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;
import net.sf.sevenzipjbinding.simple.ISimpleInArchive;
import net.sf.sevenzipjbinding.simple.ISimpleInArchiveItem;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;import java.io.*;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;public  class UnZipFile {//测试public static void main(String[] args) {try {String path="F:\\zip.zip";String descDir="F:\\1";String type = path.substring(path.lastIndexOf(".")+1);//判断文件类型if(type.equals("zip")){unZipFiles(new File(path), descDir);}else if(type.equals("rar")){unRar(new File(path), new File(descDir));}else if(type.equals("7z")){un7ZipFile(path, descDir);}else {System.out.println("只支持zip/rar/7z格式的压缩包!");}} catch (Exception e) {e.printStackTrace();}}//解压zip文件@SuppressWarnings("rawtypes")public static void unZipFiles(File zipFile, String descDir) throws Exception {File pathFile = new File(descDir);if(!pathFile.exists()){pathFile.mkdirs();}ZipFile zip = new ZipFile(zipFile);for(Enumeration entries = zip.getEntries(); entries.hasMoreElements();){ZipEntry entry =(ZipEntry)entries.nextElement();String zipEntryName = entry.getName();String str1=zipEntryName.substring(0, zipEntryName.indexOf("/"));int num=str1.length();//得到压缩文件名长度String name =zipEntryName.substring(num);//去掉压缩文件名InputStream in =zip.getInputStream(entry);String outPath =(descDir+name).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);}in.close();out.close();}System.out.println("******************解压完毕********************");}//解压rar文件public static void unRar(File sourceRar,File destDir) throws Exception  {if(!destDir.exists()){destDir.mkdirs();}Archive archive = null;FileOutputStream fos = null;System.out.println("Starting...");try {archive = new Archive(sourceRar);FileHeader fh = archive.nextFileHeader();int count = 0;File destFileName = null;while (fh != null) {String compressFileName="";// System.out.println(fh.isUnicode());// 判断文件路径是否有中文if(existZH(fh.getFileNameW())){compressFileName =fh.getFileNameW();}else{compressFileName =fh.getFileNameString();}destFileName = new File(destDir.getAbsolutePath() + "/" +compressFileName);if (fh.isDirectory()) {if (!destFileName.exists()){destFileName.mkdirs();}fh =archive.nextFileHeader();continue;}if (!destFileName.getParentFile().exists()) {destFileName.getParentFile().mkdirs();}fos = new FileOutputStream(destFileName);archive.extractFile(fh, fos);fos.close();fos = null;fh = archive.nextFileHeader();}archive.close();archive = null;System.out.println("Finished !");}catch (Exception e) {throw e;}finally {if (fos != null) {try {fos.close();fos = null;} catch (Exception e) { }}if (archive != null) {try {archive.close();archive = null;} catch (Exception e) { }}}}// 判断路径是否带中文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;}//解压7zpublic static  void un7ZipFile(String filepath,final String targetFilePath){final File file = new File(targetFilePath);if (!file.exists()) {file.mkdirs();}RandomAccessFile randomAccessFile = null;IInArchive inArchive = null;try {randomAccessFile = new RandomAccessFile(filepath, "r");inArchive = SevenZip.openInArchive(null,new RandomAccessFileInStream(randomAccessFile));ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface();for (final ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {final int[] hash = new int[] { 0 };if (!item.isFolder()) {ExtractOperationResult result;final long[] sizeArray = new long[1];result = item.extractSlow(new ISequentialOutStream() {public int write(byte[] data) throws SevenZipException {FileOutputStream fos=null;try {File tarFile=new File(file+File.separator+item.getPath());if (!tarFile.getParentFile().exists()) {tarFile.getParentFile().mkdirs();}tarFile.createNewFile();fos = new FileOutputStream(tarFile.getAbsolutePath());fos.write(data);fos.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}hash[0] ^= Arrays.hashCode(data);sizeArray[0] += data.length;return data.length;}});if (result == ExtractOperationResult.OK) {// System.out.println(String.format("%9X | %10s | %s", ////  hash[0], sizeArray[0], item.getPath()));} else {// System.err.println("Error extracting item: " + result);}}}} catch (Exception e) {e.printStackTrace();System.exit(1);} finally {if (inArchive != null) {try {inArchive.close();} catch (SevenZipException e) {e.printStackTrace();}}if (randomAccessFile != null) {try {randomAccessFile.close();} catch (IOException e) {e.printStackTrace();}}}}}

http://www.ppmy.cn/news/696750.html

相关文章

mac上安装unrar和rar解压缩工具

问题描述&#xff1a; mac上默认不支持 rar压缩&#xff0c;但是从windows过来的很多文件&#xff0c;以及邮件中的附件都是通过rar的方式进行压缩的&#xff0c;所以考虑在mac上也能够进行解压缩rar文件 步骤&#xff1a; 1&#xff1a;首先到网站click here上下载RAR 5.10 b…

支招:苹果电脑Mac版如何快速解压缩软件

在我们的日常工作中&#xff0c;解压缩文件是少不了的操作&#xff0c;如何快速有效地完成一键解压缩呢&#xff1f;今天&#xff0c;小编为大家带来苹果电脑Mac版如何快速解压缩软件&#xff0c;希望对大家有所帮助&#xff01; 解压缩zip软件是新一代文件压缩、解压工具。它体…

python 解压zip rar 7z文件

python 解压zip rar 7z文件 1、zip等格式文件解压文件2、删除临时文件3、shutil添加解压7z格式文件支持4、rar格式文件解压利用 winrar 软件进行解压 5、zip和rar文件格式 1、zip等格式文件解压文件 使用shutil&#xff0c;支持的压缩文件格式&#xff0c;一般常用解压格式为.…

Java解压压缩包(zip/rar/7z)

一、概述 主要实现解压压缩包&#xff0c;拿到压缩包中每个文件。 二、思路 针对压缩包的操作&#xff0c;首先需要拿到压缩包文件的流&#xff0c;然后利用第三方工具将流实例化&#xff0c;调用next方法迭代&#xff0c;然后分别操作压缩包中的单个文件。 三、代码实现 …

压缩文件RAR和ZIP的区别

RAR和ZIP是两种不同的压缩格式&#xff0c;它们使用是不同的压缩算法。ZIP是公开且免费的&#xff0c;很早就有了&#xff0c;可以用于任何用途。RAR是私有的&#xff0c;申请了专利&#xff0c;不公开算法细节&#xff0c;是近年才出来的算法&#xff0c;压缩率比ZIP低&#x…

java解压缩zip、rar

解压缩zip 使用hutool工具包中ZipUtil工具类 <dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.7.2</version> </dependency>// 参数是压缩包路径和编码 // GBK是为了解决中文解压缩…

压缩——实测rar压缩的各种选项对文件压缩的效果(包括固实压缩)

本文为压缩相关内容的部分内容&#xff0c;如有更新&#xff1a;https://alvincr.com/2021/01/compress-entropy/ 二&#xff1a;压缩选项 1 压缩方式 从存储—>最好&#xff0c;压缩速度依次减慢&#xff0c;但是压缩效果依次增强。 个人测试&#xff1a;为了真实感受一下…

flutter笔记:network_info_plus 模块

flutter实战之常用模块 network_info_plus模块及其应用 - 文章信息 - Author: Jack Lee (jcLee95) Visit me at: https://jclee95.blog.csdn.netEmail: 291148484163.com. Shenzhen ChineAddress of this article:https://blog.csdn.net/qq_28550263/article/details/13141787…