All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.gitee.cliveyuan.tools.ZipTools Maven / Gradle / Ivy

There is a newer version: 4.0.6
Show newest version
package com.gitee.cliveyuan.tools;

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.Objects;

/**
 * zip 压缩/解压工具
 *
 * @author clive
 * Created on 2018/07/03
 * @since: 1.0
 */
public class ZipTools {

    private static final Logger logger = LoggerFactory.getLogger(ZipTools.class);

    private ZipTools() {
    }

    /**
     * zip压缩
     *
     * @param sourcePath 源文件(夹)路径
     * @param zipFilePath zip路径
     * @throws ZipException
     */
    public static void zip(String sourcePath, String zipFilePath) throws ZipException {
        // 生成的压缩文件
        ZipFile zipFile = new ZipFile(zipFilePath);
        ZipParameters parameters = new ZipParameters();
        // 压缩方式
        parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
        // 压缩级别
        parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
        // 要打包的文件夹
        File currentFile = new File(sourcePath);
        if (currentFile.isDirectory()) {
            File[] fs = currentFile.listFiles();
            if (Objects.nonNull(fs))
                for (File f : fs) {
                    if (f.isDirectory()) {
                        zipFile.addFolder(f.getPath(), parameters);
                    } else {
                        zipFile.addFile(f, parameters);
                    }
                }
        } else  {
            zipFile.addFile(currentFile, parameters);
        }

    }

    /**
     * zip解压
     *
     * @param zipFilePath zip路径
     * @param destPath 解压路径
     * @throws ZipException
     */
    public static void unzip(String zipFilePath, String destPath) throws ZipException {
        ZipFile zipFile = new ZipFile(zipFilePath);
        zipFile.extractAll(destPath);
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy