zip4j实现文件压缩与解压缩 & common-compress压缩与解压缩

  有时候需要批量下载文件,所以需要在后台将多个文件压缩之后进行下载。

  zip4j可以进行目录压缩与文件压缩,同时可以加密压缩。

  common-compress只压缩文件,没有找到压缩目录的API。

1.zip4j的使用  

pom地址:

        <dependency>
            <groupId>net.lingala.zip4j</groupId>
            <artifactId>zip4j</artifactId>
            <version>1.3.2</version>
        </dependency>

工具类代码:

package cn.qs.utils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.springframework.util.StringUtils;

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.FileHeader;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;

/**
 * 压缩与解压缩文件工具类
 * 
 * @author Administrator
 *
 */
public class ZipUtils {
    /**
     * 根据给定密码压缩文件(s)到指定目录
     * 
     * @param destFileName
     *            压缩文件存放绝对路径 e.g.:D:/upload/zip/demo.zip
     * @param passwd
     *            密码(可为空)
     * @param files
     *            单个文件或文件数组
     * @return 最终的压缩文件存放的绝对路径,如果为null则说明压缩失败.
     */
    public static String compress(String destFileName, String passwd, File... files) {
        ZipParameters parameters = new ZipParameters();
        parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); // 压缩方式
        parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL); // 压缩级别
        if (!StringUtils.isEmpty(passwd)) {
            parameters.setEncryptFiles(true);
            parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD); // 加密方式
            parameters.setPassword(passwd.toCharArray());
        }
        try {
            ZipFile zipFile = new ZipFile(destFileName);
            for (File file : files) {
                zipFile.addFile(file, parameters);
            }
            return destFileName;
        } catch (ZipException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 根据给定密码压缩文件(s)到指定位置
     * 
     * @param destFileName
     *            压缩文件存放绝对路径 e.g.:D:/upload/zip/demo.zip
     * @param passwd
     *            密码(可为空)
     * @param filePaths
     *            单个文件路径或文件路径数组
     * @return 最终的压缩文件存放的绝对路径,如果为null则说明压缩失败.
     */
    public static String compress(String destFileName, String passwd, String... filePaths) {
        int size = filePaths.length;
        File[] files = new File[size];
        for (int i = 0; i < size; i++) {
            files[i] = new File(filePaths[i]);
        }
        return compress(destFileName, passwd, files);
    }

    /**
     * 根据给定密码压缩文件(s)到指定位置
     * 
     * @param destFileName
     *            压缩文件存放绝对路径 e.g.:D:/upload/zip/demo.zip
     * @param passwd
     *            密码(可为空)
     * @param folder
     *            文件夹路径
     * @return 最终的压缩文件存放的绝对路径,如果为null则说明压缩失败.
     */
    public static String compressFolder(String destFileName, String passwd, String folder) {
        File folderParam = new File(folder);
        if (folderParam.isDirectory()) {
            File[] files = folderParam.listFiles();
            return compress(destFileName, passwd, files);
        }
        return null;
    }

    /**
     * 根据所给密码解压zip压缩包到指定目录
     * <p>
     * 如果指定目录不存在,可以自动创建,不合法的路径将导致异常被抛出
     * 
     * @param zipFile
     *            zip压缩包绝对路径
     * @param dest
     *            指定解压文件夹位置
     * @param passwd
     *            密码(可为空)
     * @return 解压后的文件数组
     * @throws ZipException
     */
    @SuppressWarnings("unchecked")
    public static File[] deCompress(File zipFile, String dest, String passwd) throws ZipException {
        // 1.判断指定目录是否存在
        File destDir = new File(dest);
        if (destDir.isDirectory() && !destDir.exists()) {
            destDir.mkdir();
        }
        // 2.初始化zip工具
        ZipFile zFile = new ZipFile(zipFile);
        zFile.setFileNameCharset("UTF-8");
        if (!zFile.isValidZipFile()) {
            throw new ZipException("压缩文件不合法,可能被损坏.");
        }
        // 3.判断是否已加密
        if (zFile.isEncrypted()) {
            zFile.setPassword(passwd.toCharArray());
        }
        // 4.解压所有文件
        zFile.extractAll(dest);
        List<FileHeader> headerList = zFile.getFileHeaders();
        List<File> extractedFileList = new ArrayList<File>();
        for (FileHeader fileHeader : headerList) {
            if (!fileHeader.isDirectory()) {
                extractedFileList.add(new File(destDir, fileHeader.getFileName()));
            }
        }
        File[] extractedFiles = new File[extractedFileList.size()];
        extractedFileList.toArray(extractedFiles);
        return extractedFiles;
    }

    /**
     * 解压无密码的zip压缩包到指定目录
     * 
     * @param zipFile
     *            zip压缩包
     * @param dest
     *            指定解压文件夹位置
     * @return 解压后的文件数组
     * @throws ZipException
     */
    public static File[] deCompress(File zipFile, String dest) {
        try {
            return deCompress(zipFile, dest, null);
        } catch (ZipException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据所给密码解压zip压缩包到指定目录
     * 
     * @param zipFilePath
     *            zip压缩包绝对路径
     * @param dest
     *            指定解压文件夹位置
     * @param passwd
     *            压缩包密码
     * @return 解压后的所有文件数组
     */
    public static File[] deCompress(String zipFilePath, String dest, String passwd) {
        try {
            return deCompress(new File(zipFilePath), dest, passwd);
        } catch (ZipException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 无密码解压压缩包到指定目录
     * 
     * @param zipFilePath
     *            zip压缩包绝对路径
     * @param dest
     *            指定解压文件夹位置
     * @return 解压后的所有文件数组
     */
    public static File[] deCompress(String zipFilePath, String dest) {
        try {
            return deCompress(new File(zipFilePath), dest, null);
        } catch (ZipException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        // 压缩
        // compressFolder("G:/sign.zip", "123456", "G:/sign");
        // 解压
        deCompress("G:/sign.zip", "G:/unzip", "1234567");
    }
}

2.common-compress用法

  只能压缩与解压缩文件,支持多种压缩格式,比如:tar、zip、jar等格式,用法大致相同,参考官网即可。

pom地址:

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-compress</artifactId>
            <version>1.18</version>
        </dependency>
package cn.qs.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.archivers.zip.Zip64Mode;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.io.IOUtils;

public class ZipUtils {

    public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {
        doUnzipTarfile();
    }

    /**
     * 解压缩tar文件
     * 
     * @throws FileNotFoundException
     * @throws IOException
     */
    private static void doUnzipTarfile() throws FileNotFoundException, IOException {
        TarArchiveInputStream inputStream = new TarArchiveInputStream(new FileInputStream("G:/unzip/ttt.tar"));
        ArchiveEntry archiveEntry = null;
        while ((archiveEntry = inputStream.getNextEntry()) != null) {
            // h文件名称
            String name = archiveEntry.getName();
            // 构造解压出来的文件存放路径
            String entryFilePath = "G:/unzip/" + name;
            // 读取内容
            byte[] content = new byte[(int) archiveEntry.getSize()];
            inputStream.read(content);
            // 内容拷贝
            IOUtils.copy(inputStream, new FileOutputStream(entryFilePath));
        }

        IOUtils.closeQuietly(inputStream);
    }

    /**
     * 解压缩zip文件
     * 
     * @throws FileNotFoundException
     * @throws IOException
     */
    private static void doUnzipZipfile() throws FileNotFoundException, IOException {
        ZipArchiveInputStream inputStream = new ZipArchiveInputStream(new FileInputStream("G:/unzip/ttt.zip"));
        ArchiveEntry archiveEntry = null;
        while ((archiveEntry = inputStream.getNextEntry()) != null) {
            // h文件名称
            String name = archiveEntry.getName();
            // 构造解压出来的文件存放路径
            String entryFilePath = "G:/unzip/" + name;
            // 读取内容
            byte[] content = new byte[(int) archiveEntry.getSize()];
            inputStream.read(content);
            // 内容拷贝
            IOUtils.copy(inputStream, new FileOutputStream(entryFilePath));
        }

        IOUtils.closeQuietly(inputStream);
    }

    /**
     * 压缩zip
     * 
     * @throws IOException
     * @throws FileNotFoundException
     */
    private static void doCompressZip() throws IOException, FileNotFoundException {
        ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(new File("G:/unzip/ttt.zip"));
        zipOutput.setEncoding("GBK");
        zipOutput.setUseZip64(Zip64Mode.AsNeeded);
        zipOutput.setMethod(ZipArchiveOutputStream.STORED);

        // 压一个文件
        ZipArchiveEntry entry = new ZipArchiveEntry("ttt.pdf");
        zipOutput.putArchiveEntry(entry);
        FileInputStream fileInputStream = new FileInputStream(new File("G:/unzip/blank.pdf"));
        IOUtils.copyLarge(fileInputStream, zipOutput);
        IOUtils.closeQuietly(fileInputStream);
        zipOutput.closeArchiveEntry();

        // 压第二个文件
        ZipArchiveEntry entry1 = new ZipArchiveEntry("killTomcat.bat");
        zipOutput.putArchiveEntry(entry1);
        FileInputStream fileInputStream1 = new FileInputStream(new File("G:/unzip/springboot.log"));
        IOUtils.copyLarge(fileInputStream1, zipOutput);
        IOUtils.closeQuietly(fileInputStream1);
        zipOutput.closeArchiveEntry();

        IOUtils.closeQuietly(zipOutput);
    }

    /**
     * 压缩tar
     * 
     * @throws IOException
     * @throws FileNotFoundException
     */
    private static void doCompressTar() throws IOException, FileNotFoundException {
        TarArchiveOutputStream tarOut = new TarArchiveOutputStream(new FileOutputStream("G:/unzip/ttt.tar"));

        // 压一个文件
        TarArchiveEntry entry = new TarArchiveEntry("ttt.pdf");
        File file = new File("G:/unzip/ttt.pdf");
        entry.setSize(file.length());
        tarOut.putArchiveEntry(entry);
        FileInputStream fileInputStream = new FileInputStream(file);
        IOUtils.copyLarge(fileInputStream, tarOut);
        IOUtils.closeQuietly(fileInputStream);
        tarOut.closeArchiveEntry();

        // 压第二个文件
        TarArchiveEntry entry1 = new TarArchiveEntry("killTomcat.bat");
        File file2 = new File("G:/unzip/killTomcat.bat");
        entry1.setSize(file2.length());
        tarOut.putArchiveEntry(entry1);
        FileInputStream fileInputStream1 = new FileInputStream(file2);
        IOUtils.copyLarge(fileInputStream1, tarOut);
        IOUtils.closeQuietly(fileInputStream1);
        tarOut.closeArchiveEntry();

        IOUtils.closeQuietly(tarOut);
    }
}
原文地址:https://www.cnblogs.com/qlqwjy/p/10770222.html