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

简介: 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();
            }
        }
    }
}

 

目录
相关文章
|
29天前
|
Java
有关Java发送邮件信息(支持附件、html文件模板发送)
有关Java发送邮件信息(支持附件、html文件模板发送)
30 1
|
1月前
|
Java
java中替换文件内容
java中替换文件内容
14 1
|
3天前
|
Java 关系型数据库 MySQL
Elasticsearch【问题记录 01】启动服务&停止服务的2类方法【及 java.nio.file.AccessDeniedException: xx/pid 问题解决】(含shell脚本文件)
【4月更文挑战第12天】Elasticsearch【问题记录 01】启动服务&停止服务的2类方法【及 java.nio.file.AccessDeniedException: xx/pid 问题解决】(含shell脚本文件)
28 3
|
13天前
|
Java Maven
【Java报错】显示错误“Error:java: 程序包org.springframework.boot不存在“
【Java报错】显示错误“Error:java: 程序包org.springframework.boot不存在“
34 3
|
21天前
|
XML JSON JavaScript
使用JSON和XML:数据交换格式在Java Web开发中的应用
【4月更文挑战第3天】本文比较了JSON和XML在Java Web开发中的应用。JSON是一种轻量级、易读的数据交换格式,适合快速解析和节省空间,常用于API和Web服务。XML则提供更强的灵活性和数据描述能力,适合复杂数据结构。Java有Jackson和Gson等库处理JSON,JAXB和DOM/SAX处理XML。选择格式需根据应用场景和需求。
|
1月前
|
Java 数据库连接 API
Java 学习路线:基础知识、数据类型、条件语句、函数、循环、异常处理、数据结构、面向对象编程、包、文件和 API
Java 是一种广泛使用的、面向对象的编程语言,始于1995年,以其跨平台性、安全性和可靠性著称,应用于从移动设备到数据中心的各种场景。基础概念包括变量(如局部、实例和静态变量)、数据类型(原始和非原始)、条件语句(if、else、switch等)、函数、循环、异常处理、数据结构(如数组、链表)和面向对象编程(类、接口、继承等)。深入学习还包括包、内存管理、集合框架、序列化、网络套接字、泛型、流、JVM、垃圾回收和线程。构建工具如Gradle、Maven和Ant简化了开发流程,Web框架如Spring和Spring Boot支持Web应用开发。ORM工具如JPA、Hibernate处理对象与数
92 3
|
1月前
|
Java
使用java将字符串写入到指定的文件中
使用java将字符串写入到指定的文件中
11 0
|
1月前
|
XML Java 数据格式
使用java解析XML文件的步骤
使用java解析XML文件的步骤
10 0
|
Java 大数据 Apache