- 解压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();}}}}}