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

  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;
        }


		//解压7z
        public 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();
                    }
                }
            }
        }
    }
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值