java 壓縮包 遍歷解壓 zip 和 7z 指定格式檔案

FH-Admin發表於2021-07-14
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();
            }
        }
    }
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章