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

 

目录
相关文章
|
2天前
|
JSON 前端开发 Java
震惊!图文并茂——Java后端如何响应不同格式的数据给前端(带源码)
文章介绍了Java后端如何使用Spring Boot框架响应不同格式的数据给前端,包括返回静态页面、数据、HTML代码片段、JSON对象、设置状态码和响应的Header。
18 1
震惊!图文并茂——Java后端如何响应不同格式的数据给前端(带源码)
|
10天前
|
Java
java实现从HDFS上下载文件及文件夹的功能,以流形式输出,便于用户自定义保存任何路径下
java实现从HDFS上下载文件及文件夹的功能,以流形式输出,便于用户自定义保存任何路径下
20 2
java实现从HDFS上下载文件及文件夹的功能,以流形式输出,便于用户自定义保存任何路径下
|
1天前
|
存储 算法 Java
Java一分钟之-数组的创建与遍历
数组作为Java中存储和操作一组相同类型数据的基本结构,其创建和遍历是编程基础中的基础。通过不同的创建方式,可以根据实际需求灵活地初始化数组。而选择合适的遍历方法,则可以提高代码的可读性和效率。掌握这些基本技能,对于深入学习Java乃至其他编程语言的数据结构和算法都是至关重要的。
15 6
|
1天前
|
安全 Java Android开发
JavaWeb解压缩漏洞之ZipSlip与Zip炸弹
JavaWeb解压缩漏洞之ZipSlip与Zip炸弹
10 5
|
1天前
|
存储 前端开发 Java
Java后端如何进行文件上传和下载 —— 本地版(文末配绝对能用的源码,超详细,超好用,一看就懂,博主在线解答) 文件如何预览和下载?(超简单教程)
本文详细介绍了在Java后端进行文件上传和下载的实现方法,包括文件上传保存到本地的完整流程、文件下载的代码实现,以及如何处理文件预览、下载大小限制和运行失败的问题,并提供了完整的代码示例。
37 1
|
12天前
|
Java
java小工具util系列5:java文件相关操作工具,包括读取服务器路径下文件,删除文件及子文件,删除文件夹等方法
java小工具util系列5:java文件相关操作工具,包括读取服务器路径下文件,删除文件及子文件,删除文件夹等方法
26 4
|
11天前
|
安全 Java Android开发
JavaWeb解压缩漏洞之ZipSlip与Zip炸弹
JavaWeb解压缩漏洞之ZipSlip与Zip炸弹
30 2
|
13天前
|
域名解析 分布式计算 网络协议
java遍历hdfs路径信息,报错EOFException
java遍历hdfs路径信息,报错EOFException
26 3
|
14天前
|
Java
Java-FileInputStream和FileOutputStream的使用,txt文件及图片文件的拷贝
这篇文章介绍了Java中FileInputStream和FileOutputStream的使用,包括如何读取和写入txt文件以及如何拷贝图片文件。
Java-FileInputStream和FileOutputStream的使用,txt文件及图片文件的拷贝
|
5月前
|
Java
java面向对象——包+继承+多态(一)-2
java面向对象——包+继承+多态(一)
39 3