java 压缩包 遍历解压 zip 和 7z 指定格式文件

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry;
import org.apache.commons.compress.archivers.sevenz.SevenZFile;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Enumeration;
import java.util.concurrent.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * zip文件解压
 * @author fhadmin
 * @from  fhadmin.cn
 */
@Slf4j
public class ZipUtils {
    public static void main(String[] args) throws IOException {
//        ZipHandler zipHandler = new ZipHandler();
//        zipHandler.decompress("F:/test.zip", "F:/test/");
        String filePath = "C:\\Users\\260481\\Desktop\\1ORIGIN_DATA_LIST_1610090555026_spark9.zip";
        File fil = new File(filePath);
        InputStream fileInputStream = new FileInputStream(fil);
        Path path = Paths.get("business","src", "main", "resources", "static", "1ORIGIN_DATA_LIST_1610615443346_测试.zip");
        File file1 = path.getParent().toFile();
        if (!file1.exists()){
            file1.mkdirs();
        }
        Files.copy(fileInputStream,path);
        File file = path.toFile();
        ZipUtils zipHandler = new ZipUtils();
        Path path1 = Paths.get("business","src", "main", "resources", "static");
        zipHandler.decompress(file,path1.toString());
    }

//解压方法
    public  void decompress(File srcFile, String destDirPath){
//判断是zip格式 还是 7z格式
        if (srcFile.getName().toLowerCase().endsWith(".zip")){
                try {
                    decompressZIP(srcFile, destDirPath);
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }else if (srcFile.getName().toLowerCase().endsWith(".7z")){
               try {
decompress7Z(srcFile, destDirPath);
               } catch (Exception e) {
                   e.printStackTrace();
               }
        }
//解压完成后,删除压缩包方法,以及空文件夹
        File parentFile = srcFile.getParentFile();
        boolean delete = srcFile.delete();
        if (!delete){
            log.error("删除文件"+srcFile.getName()+"失败");
        }
        if (parentFile.isDirectory() && (parentFile.listFiles() == null || parentFile.listFiles().length<=0)){
            log.info("删除文件夹"+parentFile.getName()+parentFile.delete());
        }
    }

    private  void decompress7Z(File srcFile, String destDirPath) throws Exception {
        /**
         * zip解压
         * @param inputFile 待解压文件名
         * @param destDirPath  解压路径
         */
//        File srcFile = new File(inputFile);//获取当前压缩文件
        // 判断源文件是否存在
        if (!srcFile.exists()) {
            throw new Exception(srcFile.getPath() + "所指文件不存在");
        }
        //开始解压
        long start = System.currentTimeMillis();
        SevenZFile zIn = new SevenZFile(srcFile);
        SevenZArchiveEntry entry = null;
        File file = null;
        while ((entry = zIn.getNextEntry()) != null) {
            if (!entry.isDirectory()) {

                String name = entry.getName();

                file = new File(destDirPath, name);
                saveFile(zIn, file,destDirPath);

            }
        }

        zIn.close();
        long end = System.currentTimeMillis();
        log.info("解压"+srcFile.getName()+"耗时"+(end-start)+"毫秒");
    }

    private void saveFile(SevenZFile zIn, File file, String destDirPath) {

        String toLowerCase = file.getName().toLowerCase();
        //校验文件后缀
        if (!file.exists() &&  (verifySuffix(toLowerCase) || toLowerCase.endsWith(".zip")|| toLowerCase.endsWith(".7z"))) {
            new File(file.getParent()).mkdirs();//创建此文件的上级目录
            try(OutputStream out = new FileOutputStream(file);
                BufferedOutputStream bos = new BufferedOutputStream(out);) {

                int len = -1;
                byte[] buf = new byte[1024];
                while ((len = zIn.read(buf)) != -1) {
                    bos.write(buf, 0, len);
                }

            } catch (IOException e) {
                log.error(file.getName() + "文件创建失败");
            }

            if (file.getName().endsWith(".7z") || file.getName().endsWith(".zip")){
                try {
                    decompress(file, destDirPath);
//                            boolean delete = file.delete();
//                            System.out.println("文件删除"+delete);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        } else {
//            file = new File(file.getParent(), "(1)" + file.getName());
//            saveFile(zIn, file, destDirPath);
        }
    }

    private void decompressZIP(File file, String destPath) throws IOException {

        long start = System.currentTimeMillis();

        ZipFile zipFile = new ZipFile(file, Charset.forName("GBK"));

        Enumeration<? extends ZipEntry> entries = zipFile.entries();
//使用线程池 提交任务  没有工具类 可自己new
        ExecutorService threadPool = ThreadPoolUtil.getInstance();
        int size = zipFile.size();
        final CountDownLatch countDownLatch = new CountDownLatch(size);
        while (entries.hasMoreElements()) {
            ZipEntry zipEntry = entries.nextElement();
            if (zipEntry.isDirectory()) {
                countDownLatch.countDown();
                continue;
            }
            threadPool.execute(new FileWritingTask(zipFile,destPath,zipEntry,countDownLatch));
        }
//        threadPool.shutdown();
        try {
//            threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
      countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        zipFile.close();
        long end = System.currentTimeMillis();
        log.info("解压"+file.getName()+"耗时"+(end-start)+"毫秒");
//        boolean delete = file.delete();
//        if (!delete){
//            log.error("删除文件"+file.getName()+"失败");
//        }

    }

    public static boolean verifySuffix(String name) {
        String lowerCase = name.toLowerCase();
        if (lowerCase.endsWith(".jpg") || lowerCase.endsWith(".jpeg") || lowerCase.endsWith(".png") || lowerCase.endsWith(".bmp")){
            return true;
        }else {
            return false;
        }
    }

    private class FileWritingTask implements Runnable {
        private ZipFile zipFile;

        private String destPath;
        private ZipEntry zipEntry;
        private CountDownLatch countDownLatch;
            FileWritingTask(ZipFile zipFile, String destPath, ZipEntry zipEntry, CountDownLatch countDownLatch) {
            this.zipFile = zipFile;
            this.destPath = destPath;
            this.zipEntry = zipEntry;
            this.countDownLatch = countDownLatch;
        }

        @Override
        public void run() {
            try {
                String name = zipEntry.getName();
                String lowerCaseName = name.toLowerCase();
                if (verifySuffix(lowerCaseName)|| lowerCaseName.endsWith(".zip")|| lowerCaseName.endsWith(".7z")){
                    //保留层级目录 解决文件重名问题
//                    if (name.lastIndexOf("/")!=-1) {
//                        name = name.substring(name.lastIndexOf("/")+1);
//                    }
                    File file = new File(destPath + File.separator + name);
                    while(!file.exists() ){
//                        file=new File(destPath+File.separator+"(1)"+name);
                        File parentFile = file.getParentFile();
                        if (!parentFile.exists()) {
                            parentFile.mkdirs();
                        }
                        try {
                            InputStream inputStream = zipFile.getInputStream(this.zipEntry);
//                            Path path = Paths.get(parentFile.getPath() + File.separator + name);
//File file1 = new File(path.toString());
                            while (!file.exists()) {
                                Files.copy(inputStream,Paths.get(file.getPath()));
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        //判断如果是压缩包 递归解压
                        if (lowerCaseName.endsWith(".zip")|| lowerCaseName.endsWith(".7z")){
                            String s = destPath + File.separator + name;
                            File file1 = new File(s);
                            decompress(file1,destPath);
                        }
                    }

                }
            }finally {
                countDownLatch.countDown();
            }
        }
    }
}
(0)

相关推荐

  • 如何将文件打成zip包并下载

    @FunctionDesc("下载附件") @RequestMapping(value = "/exportAttachments", method = Req ...

  • 压缩包的解压使用小技巧

    相信很多人都会遇到压缩包下载的问题,但是,也有一些人因为没有良好的解压习惯导致文件在桌面显示的杂乱不堪,像是这样. 下载一个winrar的压缩包,解压到当前界面,显示如上图. 假如我们换种解压方式,像 ...

  • 压缩包的解压密码如何找回

    压缩包带有压缩打开密码,这是对压缩包的一种加密,如果想要解压文件就必须输入密码才行,没有办法绕过密码解压文件,如果你没有密码还想要解压文件的话,可以使用奥凯丰 压缩包解密大师尝试将密码找到.然后再进行 ...

  • 压缩包密码都在哪?高手教你找到RAR解压密码

    有很多朋友反馈在网上下载了文件,是压缩包格式,但是右键解压的时候却发现要密码,那么这个密码在哪里查看呢,下面小编以自己上网下载多年的经验分享下如何找到解压密码. 压缩包密码都在哪看? 1.一般在你下载 ...

  • 阿里云盘如何解压压缩包

    相信有一些网友由于对如何解压压缩包不够熟悉,可能还不晓得阿里云盘如何解压压缩包,那么下面小编就来分享关于阿里云盘解压压缩包的教程. 阿里云盘暂不支持直接解压获取压缩包文件,需要下载文件后,在手机中进行 ...

  • 如何尽可能找到百度网盘分享的压缩包解压密码?

    天天有人求解压密码 最近看到好多网友在回复求解压密码, 在这我统一回复下:      我这也没有解压密码      是真的没有!!! 我很能体会那种感觉, 自己辛辛苦苦挂机下了一个通宵的文件最后居然要 ...

  • 一秒解压 龙湖吞下的北塘压缩包地块周边究竟都有啥

    在331限购政策出台一个月后,天津楼市成交环比下降5成.作为5月土拍的重头戏,滨海北塘10 in 1压缩版巨无霸地块的拍卖受到了众多关注.出乎所有人意料的是--现场甚至没有举牌,拍卖师三次询问有没有买 ...

  • 十天干解压方式大合集.zip

    2019/5/9 这是「乾小鲲」第92次和你见面 " 十天干解压方式 大合集 " 考试.论文.DDL 奔波.加班.996 来自生活的鸭力 似乎无处不在 让你在不断陷入自闭的同时 还 ...

  • 2018高考解压全国卷.zip

    「整个词」第二期,高考来了. 这是首批00后人生的第一次大考.之后,90后老前辈们逐渐失去C位,00后将站在全民枪口上接棒. 朋友圈又迎来了集体缅怀青春的高潮,80.90后老前辈已叉好腰准备给年轻人分 ...

  • 《古典轻音乐》优美动听的音乐带走你的疲惫和烦恼,舒缓解压失眠

    《古典轻音乐》优美动听的音乐带走你的疲惫和烦恼,舒缓解压失眠