JAVA使用Zip工具包压缩文件为zip格式(1)——单文件压缩

JAVA使用Zip工具包压缩文件为zip格式(1)——单文件压缩

一、使用场景概述

将文件压缩为zip格式的需求,避免踩坑,这篇文章教大家如何使用java.util.zipjava-io进行文件的zip格式压缩。
本章仅适用于单个文件压缩,后续会持续更新,多个文件、文件夹压缩,点个关注,不迷路哦!

二、准备工作

  • 开发环境
    java 1.8
    springboot2.0版本
    maven
  • 相关依赖
    jdk 1.8提供

三、具体实现

涉及的主要类:ZipOutputStream(压缩文件流处理类)
大家可以根据自己需求将以下代码封装为工具类,这样拿到哪里都可以用:

1. 实现代码

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/** Zip工具类
 * @author getao
 * @date 2022/7/1 16:31
 */
public class ZipUtils {
   /**
     * 压缩文件到指定路径
     * @param sourcePath 源文件路径
     * @param targetZipPath 目标路径
     */
    public static void pathTOZipFile(String sourcePath, String targetZipPath) {
        File sourceFile = new File(sourcePath);
        File targetZipFile = new File(targetZipPath);
        // 如果目标路径不存在,就创建父级目录,暂不考虑系统权限问题
        if (!targetZipFile.getParentFile().exists()) {
            targetZipFile.getParentFile().mkdir();
        }
        try {
            // 创建目标压缩文件保存路径输出流
            FileOutputStream outputStream = new FileOutputStream(targetZipFile);
            ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
            // 如果是单个文件
            ZipEntry zipEntry = new ZipEntry(sourceFile.getName());
            zipOutputStream.putNextEntry(zipEntry);
            FileInputStream inputStream = new FileInputStream(sourceFile);
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len=inputStream.read(buffer)) >=0 ) {
                zipOutputStream.write(buffer, 0, len);
            }
            // 释放资源
            zipOutputStream.close();
            inputStream.close();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /** 可使用以下代码测试,注意更换为自己电脑中的路径
 	 * @author getao
 	 * @date 2022/7/1 16:31
 	 */
    public static void main(String[] args) throws IOException, FileNotFoundException {
        // 源文件路径
        String sourcePath = "C:\\Users\\getao\\Desktop\\s3afn5yfmjj.jpg";
        // 压缩路径
        String targetPath = "C:\\Users\\getao\\Desktop\\james.zip";
        // 调用压缩方法
        pathTOZipFile(sourcePath, targetPath);
        System.out.println("文件:" + sourcePath + "压缩成功啦!");
    }
}

2. 测试结果

叮~亲测有效,到你的压缩位置看下,文件可以正常解压并浏览,大功告成!!!

文件:C:\Users\getao\Desktop\s3afn5yfmjj.jpg压缩成功啦!

Process finished with exit code 0

如果有其他好的想法,欢迎评论区交流。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值