JAVA实现zip压缩

需要:JDK1.8 或以上版本

参考资料:https://www.cnblogs.com/stromgao/p/16086838.html

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipUtils {

    /**
     * 压缩<br>
     * 支持单个或者多个目录或文件<br>
     * 支持多层目录文件,保留空目录<br>
     * 
     * @param destFile
     * @param srcFiles
     * @throws Exception
     */
    public static void zip(File destFile, File... srcFiles) throws Exception {

        try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(destFile))) {

            for (File file : srcFiles) {
                if (file == null || !file.exists()) {
                    continue;
                }

                recursionCompress(zos, file, file.getName());
            }

        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 递归压缩
     * 
     * @param zos          zip输出流
     * @param srcFile      要压缩的文件
     * @param zipEntryName 压缩后的zip节点名
     * @throws Exception
     */
    private static void recursionCompress(ZipOutputStream zos, File srcFile, String zipEntryName) throws Exception {

        // 如果是目录,则创建目录并递归压缩子文件
        if (srcFile.isDirectory()) {
            // 添加目录
            zos.putNextEntry(new ZipEntry(zipEntryName + File.separator));
            zos.closeEntry();

            // 遍历并压缩子文件
            for (File subFile : srcFile.listFiles()) {
                String subZipEntryName = zipEntryName + File.separator + subFile.getName();
                recursionCompress(zos, subFile, subZipEntryName);
            }

            return;
        }

        // 如果是文件,则压缩文件
        zos.putNextEntry(new ZipEntry(zipEntryName));

        try (FileInputStream inputStream = new FileInputStream(srcFile)) {

            int len;
            byte[] buf = new byte[2 * 1024];

            while ((len = inputStream.read(buf)) != -1) {
                zos.write(buf, 0, len);
            }

        } catch (Exception e) {
            throw e;
        }

        zos.closeEntry();
    }

    public static void main(String[] args) throws Exception {

        ZipUtils.zip(new File("C:/Users/Chao/Desktop/ziptest/aaa.zip"),
                new File("C:/Users/Chao/Desktop/ziptest/folder/"));

        ZipUtils.zip(new File("C:/Users/Chao/Desktop/ziptest/bbb.zip"),
                new File("C:/Users/Chao/Desktop/ziptest/folder/").listFiles());

        System.out.println("finished!");
    }

}

 

posted @ 2022-09-16 18:01  dianchaozhang  阅读(1241)  评论(0编辑  收藏  举报