张洋洋
2025-01-08 29723c0c6658effce1419aadc01354853965ec6d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package com.se.simu.utils;
 
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ZipUtil;
import org.apache.commons.io.FileUtils;
 
import java.io.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
 
/**
 * zip
 */
public class ZipUtils {
    // 解压zip格式
    public static void unzip(String zipFilePath, String destDir){
        //所有的文件路径
        List<String> filePaths = new ArrayList<>();
 
        File destDirectory = new File(destDir);
        if (!destDirectory.exists()) {
            if (!destDirectory.mkdirs()) {
            }
        }
        try (ZipFile zipFile = new ZipFile(zipFilePath)) {
            Enumeration<? extends ZipEntry> entries = zipFile.entries();
 
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                String filePath = destDir + File.separator + entry.getName();
                // 确保目标文件路径的父目录存在
                File entryDestination = new File(filePath);
                File parentDirectory = entryDestination.getParentFile();
                if (parentDirectory != null && !parentDirectory.exists()) {
                    parentDirectory.mkdirs();
                }
                if (!entry.isDirectory()) {
                    // 提取文件
                    try (InputStream is = zipFile.getInputStream(entry);
                         BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath))) {
                        byte[] bytesIn = new byte[4096];
                        int read;
                        while ((read = is.read(bytesIn)) != -1) {
                            bos.write(bytesIn, 0, read);
                        }
                    }
                    // 打印文件路径
                    filePaths.add(filePath);
                } else {
                    // 如果是目录,则创建目录(注意:在上面的mkdirs调用中已经处理了)
                    // 这里也可以选择打印目录路径
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            try {
                File file = ZipUtil.unzip(zipFilePath, destDir, CharsetUtil.CHARSET_GBK);
                File[] file1 = file.listFiles();
                for (int i = 0; i < file1.length; i++) {
                    filePaths.add(file1[i].getAbsolutePath());
                }
            } catch (Exception ex) {
                e.printStackTrace();
            }
        }
    }
}