文件压缩zip工具

文件压缩及解压缩

不废话上代码

public class ZipFileUtil {

    /**
     * 日志记录器,用于记录ZipFileUtil类中的日志信息
     */
    private static final Logger log = LoggerFactory.getLogger(ZipFileUtil.class);


    /**
     * 压缩多个文件成一个zip文件
     *
     * @param srcFiles:源文件列表
     * @param destZipFile:压缩后的文件
     */
    public static void toZip(List<File> srcFiles, File destZipFile) {
        byte[] buf = new byte[1024];
        try {
            // ZipOutputStream类:完成文件或文件夹的压缩
            ZipOutputStream out = new ZipOutputStream(Files.newOutputStream(destZipFile.toPath()));
            for (File srcFile : srcFiles) {
                FileInputStream in = new FileInputStream(srcFile);
                // 给列表中的文件单独命名
                out.putNextEntry(new ZipEntry(srcFile.getName()));
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                out.closeEntry();
                in.close();
            }
            out.close();
        } catch (Exception e) {
            log.error("压缩文件失败,", e);
        }
    }

    /**
     * 解压缩指定的 ZIP 文件到指定的输出目录
     *
     * @param zipFile 待解压的 ZIP 文件
     * @param outDir  解压后的输出目录
     * @throws Exception 如果解压过程中发生错误
     */
    public static void unZip(File zipFile, String outDir) throws Exception {
        if (zipFile == null || !zipFile.exists() || zipFile.length() == 0) {
            throw new FileNotFoundException();
        }
        final ZipInputStream zipInputStream = new ZipInputStream(Files.newInputStream(zipFile.toPath()));
        ZipEntry entry;
        while ((entry = zipInputStream.getNextEntry()) != null) {
            if (!entry.isDirectory()) {
                final File file = new File(outDir, entry.getName());
                if (!file.exists()) {
                    file.getParentFile().mkdirs();
                }

                final FileOutputStream fileOutputStream = new FileOutputStream(file);
                final BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
                int len;
                final byte[] bytes = new byte[1024];
                while ((len = zipInputStream.read(bytes)) != -1) {
                    bufferedOutputStream.write(bytes, 0, len);
                }
                bufferedOutputStream.close();
                fileOutputStream.close();
            }
            zipInputStream.closeEntry();
        }
        zipInputStream.close();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值