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

 

目录
相关文章
|
消息中间件 算法 安全
JUC并发—1.Java集合包底层源码剖析
本文主要对JDK中的集合包源码进行了剖析。
|
前端开发 JavaScript Java
[Java计算机毕设]基于ssm的OA办公管理系统的设计与实现,附源码+数据库+论文+开题,包安装调试
OA办公管理系统是一款基于Java和SSM框架开发的B/S架构应用,适用于Windows系统。项目包含管理员、项目管理人员和普通用户三种角色,分别负责系统管理、请假审批、图书借阅等日常办公事务。系统使用Vue、HTML、JavaScript、CSS和LayUI构建前端,后端采用SSM框架,数据库为MySQL,共24张表。提供完整演示视频和详细文档截图,支持远程安装调试,确保顺利运行。
556 17
|
Java Android开发
Eclipse 创建 Java 包
Eclipse 创建 Java 包
313 1
|
存储 Java API
Java实现导出多个excel表打包到zip文件中,供客户端另存为窗口下载
Java实现导出多个excel表打包到zip文件中,供客户端另存为窗口下载
1184 4
|
Java Apache Maven
Java/Spring项目的包开头为什么是com?
本文介绍了 Maven 项目的初始结构,并详细解释了 Java 包命名惯例中的域名反转规则。通过域名反转(如 `com.example`),可以确保包名的唯一性,避免命名冲突,提高代码的可读性和逻辑分层。文章还讨论了域名反转的好处,包括避免命名冲突、全球唯一性、提高代码可读性和逻辑分层。最后,作者提出了一个关于包名的问题,引发读者思考。
1281 0
Java/Spring项目的包开头为什么是com?
|
安全 Java Android开发
JavaWeb解压缩漏洞之ZipSlip与Zip炸弹
JavaWeb解压缩漏洞之ZipSlip与Zip炸弹
909 5
|
Java API 数据处理
Java 包(package)的作用详解
在 Java 中,包(package)用于组织和管理类与接口,具有多项关键作用:1)系统化组织代码,便于理解和维护;2)提供命名空间,避免类名冲突;3)支持访问控制,如 public、protected、默认和 private,增强封装性;4)提升代码可维护性,实现模块化开发;5)简化导入机制,使代码更简洁;6)促进模块化编程,提高代码重用率;7)管理第三方库,避免命名冲突;8)支持 API 设计,便于功能调用;9)配合自动化构建工具,优化项目管理;10)促进团队协作,明确模块归属。合理运用包能显著提升代码质量和开发效率。
1613 4
|
Java 数据安全/隐私保护
Java 包(package)的使用详解
Java中的包(`package`)用于组织类和接口,避免类名冲突并控制访问权限,提升代码的可维护性和可重用性。通过`package`关键字定义包,创建相应目录结构即可实现。包可通过`import`语句导入,支持导入具体类或整个包。Java提供多种访问权限修饰符(`public`、`protected`、`default`、`private`),以及丰富的标准库包(如`java.lang`、`java.util`等)。合理的包命名和使用对大型项目的开发至关重要。
1562 3
|
安全 Java Android开发
JavaWeb解压缩漏洞之ZipSlip与Zip炸弹
JavaWeb解压缩漏洞之ZipSlip与Zip炸弹
634 2
|
安全 Java API
JAVA并发编程JUC包之CAS原理
在JDK 1.5之后,Java API引入了`java.util.concurrent`包(简称JUC包),提供了多种并发工具类,如原子类`AtomicXX`、线程池`Executors`、信号量`Semaphore`、阻塞队列等。这些工具类简化了并发编程的复杂度。原子类`Atomic`尤其重要,它提供了线程安全的变量更新方法,支持整型、长整型、布尔型、数组及对象属性的原子修改。结合`volatile`关键字,可以实现多线程环境下共享变量的安全修改。