Zip解压工具类

import lombok.extern.slf4j.Slf4j;
import lombok.extern.log4j.Log4j;
import org.jeecg.common.exception.JeecgBootException;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * @author:
 * @date: 2022年08月30日 9:14
 */
@Slf4j
public class ZipUtil {


    /**
     * 解压到目标路径
     *
     * @param srcFile  文件
     * @param savePath 目标路径
     * @return
     */
    public static void unZip(MultipartFile srcFile, String savePath) {
        FileOutputStream out = null;
        BufferedOutputStream bos = null;
        try {
            File file = null;
            InputStream ins = srcFile.getInputStream();
            clearFiles(savePath);
            File file2 = new File(savePath);
            File file3 = new File(savePath + "/zip/");
            if (!file2.exists()) {
                file2.mkdirs();//创建目录
            }
            if (!file3.exists()) {
                file3.mkdirs();
//                throw new RuntimeException(file.getPath() + ",file is not found");
            }

            file = new File(savePath + "/zip/" + srcFile.getOriginalFilename());

            inputStreamToFile(ins, file);
            //读取压缩文件
            ZipInputStream in = new ZipInputStream(new FileInputStream(file), Charset.forName("GBK"));
            //zip文件实体类
            ZipEntry entry;
            //遍历压缩文件内部 文件数量
            while ((entry = in.getNextEntry()) != null) {
                if (!entry.isDirectory()) {
                    //文件输出流
                    out = new FileOutputStream(savePath + "/" + getFileExtension2(entry.getName()));

                    bos = new BufferedOutputStream(out);
                    int len;
                    byte[] buf = new byte[1024];
                    while ((len = in.read(buf, 0, 1024)) != -1) {
                        bos.write(buf, 0, len);
                    }
                }
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new JeecgBootException("读取异常");
        } finally {
            try {
                bos.close();
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[512];
            while ((bytesRead = ins.read(buffer, 0, 512)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取路径下所有的文件
     *
     * @param savePath 目标路径
     * @return
     */
    public static List<File> getSubFiles(String savePath) throws Exception {
        List<File> fileList = new ArrayList<>();
        File file = new File(savePath);
        File[] files = file.listFiles();
        for (File fileIndex : files) {
            if (!fileIndex.exists()) {
                throw new NullPointerException("Cannot find " + fileIndex);
            } else if (fileIndex.isFile()) {
                fileList.add(fileIndex);
            } else {
                if (fileIndex.isDirectory()) {
                    getSubFiles(fileIndex.getAbsolutePath());
                }
            }
        }
        return fileList;
    }


    /**
     * 将匹配到的非法字符以空替换
     *
     * @param fileName 获取的文件名
     * @return
     */
    public String illegalCharacterHandling(String fileName) {
        Pattern pattern = Pattern.compile("[\\s\\\\/:\\*\\?\\\"<>\\|]");
        Matcher matcher = pattern.matcher(fileName);
        return matcher.replaceAll("");
    }


    /**
     * 删除路径及路径下所有文件
     *
     * @param savePath 路径
     * @return
     */
    public static void clearFiles(String savePath) {
        File file = new File(savePath);
        deleteFile(file);
    }

    public static void deleteFile(File file) {
        if (file.exists()) {
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    deleteFile(files[i]);
                }
            }
        }
        file.delete();
    }


    public static boolean deleteFiles(String delpath) {
        try {
            File file = new File(delpath);
            // 当且仅当此抽象路径名表示的文件存在且 是一个目录时,返回 true
            if (!file.isDirectory()) {
                file.delete();
            } else if (file.isDirectory()) {
                String[] filelist = file.list();
                for (int i = 0; i < filelist.length; i++) {
                    File delfile = new File(delpath + "\\" + filelist[i]);
                    if (!delfile.isDirectory()) {
                        delfile.getAbsoluteFile().delete();
                        log.debug(delfile.getAbsolutePath() + "删除文件成功");
                    } else if (delfile.isDirectory()) {
                        deleteFiles(delpath + "\\" + filelist[i]);
                    }
                }
                log.debug(file.getAbsolutePath() + "删除成功");
                file.getAbsoluteFile().delete();
            }
        } catch (Exception e) {
            System.out.println("deletefile() Exception:" + e.getMessage());
        }
        return true;
    }


    //获取文件名称后缀
    public static String getFileExtension(MultipartFile file) {
        if (file == null) {
            return "";
        }
        String fileName = file.getOriginalFilename();
        if (StringUtils.isEmpty(fileName)) {
            fileName = file.getName();
        }
        if (fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0)
            return fileName.substring(fileName.lastIndexOf(".") + 1);
        else return "";
    }

    //获取文件名称后缀
    public static String getFileExtension2(String str) {

        if (str.lastIndexOf(".") != -1 && str.lastIndexOf(".") != 0)
            return str.substring(str.lastIndexOf("/") + 1);
        else return "";
    }


    //获取文件名称
    public static String getFileBefore(MultipartFile file, String con) {
        if (file == null) {
            return "";
        }
        String fileName = file.getOriginalFilename();
        if (StringUtils.isEmpty(fileName)) {
            fileName = file.getName();
        }
        if (fileName.lastIndexOf(con) != -1 && fileName.lastIndexOf(con) != 0)
            return fileName.substring(0, fileName.lastIndexOf(con));
        else return "";
    }

    //获取文件大小是否符合规则
    public static Boolean getFileSize(MultipartFile file, int size, String unit) {
        if (file == null) {
            return false;
        }
        double fileSize = 0;
        switch (unit.toUpperCase()) {
            case "B":
                fileSize = (double) file.getSize();
                break;
            case "K":
                fileSize = (double) file.getSize() / 1024;
                break;
            case "M":
                fileSize = (double) file.getSize() / 1028576;
                break;
            case "G":
                fileSize = (double) file.getSize() / 107341824;
                break;
            default:
                return false;
        }
        if (fileSize > size) {
            return false;
        }
        return true;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值