Java 压缩包(zip)解压工具类


package com.demo.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * @author lyu
 * @description:
 * @create 2024-11-29 10:26
 */
public class ZipUtil {
    private static final Logger log = LoggerFactory.getLogger(ZipUtil.class);

    private ZipUtil() {
        throw new UnsupportedOperationException("Disabled use refection to create instance!!!");
    }

    public static void decompression(String zipPath, String targetDir) throws IOException {
        log.info("Path--->当前解压的文件为:{}", zipPath);
        InputStream inputStream = Files.newInputStream(Paths.get(zipPath));
        byte[] bytes = FileCopyUtils.copyToByteArray(inputStream);
        unzip(bytes, targetDir);
    }

    public static void decompression(File file, String targetDir) throws IOException {
        FileInputStream inputStream = new FileInputStream(file);
        log.info("File--->当前解压的文件为:{}", file.getName());
        byte[] bytes = FileCopyUtils.copyToByteArray(inputStream);
        unzip(bytes, targetDir);
    }

    public static void decompression(MultipartFile file, String targetDir) throws IOException {
        String filename = file.getOriginalFilename();
        log.info("MultipartFile--->当前解压的文件为:{}", filename);
        byte[] bytes = file.getBytes();
        unzip(bytes, targetDir);
    }

    public static void unzip(byte[] bytes, String targetDir) {
        try (ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(bytes), getCharset(bytes));) {
            unzip(zipInputStream, targetDir);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }

    public static void unzip(ZipInputStream zipIn, String targetDir) throws IOException {
        File file = new File(targetDir);
        if (!file.exists()) {
            boolean mkdir = file.mkdir();
            log.debug("创建目标文件{}是否成功:{}", targetDir, mkdir);
        }
        ZipEntry entry;
        while ((entry = zipIn.getNextEntry()) != null) {
            String filePath = targetDir + File.separator + entry.getName();
            if (entry.isDirectory()) {
                File dir = new File(filePath);
                boolean mkdirs = dir.mkdirs();
                log.info("压缩包文件夹:{},是否创建成功:{}", filePath, mkdirs);
            } else {
                extractFile(zipIn, filePath);
            }
            zipIn.closeEntry();
        }
    }

    private static void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
        try (FileOutputStream fos = new FileOutputStream(filePath)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = zipIn.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
        }
    }

    private static Charset getCharset(byte[] bytes) throws IOException {
        InputStream bis = new ByteArrayInputStream(bytes);
        int test = bis.read();
        int secondTest = bis.read();
        if (test == 0xEF && secondTest == 0xBB) {
            return StandardCharsets.UTF_8;
        } else {
            return Charset.forName("GBK");
        }
    }

    public static void main(String[] args) throws IOException {
        String zip = "E:\\utils.zip";
        String str = "E:\\test\\lol";
        //方式一
        decompression(zip, str);
        //方式二
        decompression(new File(zip), str);
        //方式三
        MockMultipartFile multipartFile = new MockMultipartFile("files", "utils.zip", "application/zip", Files.newInputStream(Paths.get(zip)));
        decompression(multipartFile, str);
    }
}

posted @ 2024-11-29 11:32  lyu6  阅读(183)  评论(0)    收藏  举报