Java8 Zip 压缩与解压缩的实现

 更新时间:2020年03月25日 09:32:55   作者:sp42a  
这篇文章主要介绍了Java8 Zip 压缩与解压缩的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

网上找过几个例子都有点小问题,还是谷歌找出来的靠谱。主要是增加了指定文件的功能,通过 Java8 的 Lambda 判断是否加入 ZIP 压缩,比较方便。函数表达式的签名是 Function<File, Boolean>,参数是待加入的 File 对象,返回值 true 表示允许,反之不行。

完整代码在:https://gitee.com/sp42_admin/ajaxjs/blob/master/ajaxjs-base/src/main/java/com/ajaxjs/util/io/FileHelper.java

/**
 * Copyright sp42 frank@ajaxjs.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ajaxjs.util.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.function.Function;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import com.ajaxjs.util.logger.LogHelper;

/**
 * ZIP 压缩/解压缩
 * 
 * @author sp42
 *
 */
public class ZipHelper {
 private static final LogHelper LOGGER = LogHelper.getLog(ZipHelper.class);

 /**
 * 解压文件
 * 
 * @param save  解压文件的路径,必须为目录
 * @param zipFile 输入的解压文件路径,例如C:/temp/foo.zip或 c:\\temp\\bar.zip
 */
 public static void unzip(String save, String zipFile) {
 if (!new File(save).isDirectory())
  throw new IllegalArgumentException("保存的路径必须为目录路径");

 long start = System.currentTimeMillis();
 File folder = new File(save);
 if (!folder.exists())
  folder.mkdirs();

 try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));) {
  ZipEntry ze;
  while ((ze = zis.getNextEntry()) != null) {
  File newFile = new File(save + File.separator + ze.getName());
  System.out.println("file unzip : " + newFile.getAbsoluteFile());

  // 大部分网络上的源码,这里没有判断子目录
  if (ze.isDirectory()) {
   newFile.mkdirs();
  } else {
//   new File(newFile.getParent()).mkdirs();
   FileHelper.initFolder(newFile);
   FileOutputStream fos = new FileOutputStream(newFile);
   IoHelper.write(zis, fos, false);
   fos.close();
  }

//  ze = zis.getNextEntry();
  }
  zis.closeEntry();
 } catch (IOException e) {
  LOGGER.warning(e);
 }

 LOGGER.info("解压缩完成,耗时:{0}ms,保存在{1}", System.currentTimeMillis() - start, save);
 }

 /**
 * 压缩文件
 * 
 * @param toZip  要压缩的目录或文件
 * @param saveZip 压缩后保存的 zip 文件名
 */
 public static void zip(String toZip, String saveZip) {
 zip(toZip, saveZip, null);
 }

 /**
 * 压缩文件
 * 
 * @param toZip   要压缩的目录或文件
 * @param saveZip  压缩后保存的 zip 文件名
 * @param everyFile 输入 File,可在这 Lambda 里面判断是否加入 ZIP 压缩,返回 true 表示允许,反之不行
 */
 public static void zip(String toZip, String saveZip, Function<File, Boolean> everyFile) {
 long start = System.currentTimeMillis();
 File fileToZip = new File(toZip);

 FileHelper.initFolder(saveZip);

 try (FileOutputStream fos = new FileOutputStream(saveZip); ZipOutputStream zipOut = new ZipOutputStream(fos);) {
  zip(fileToZip, fileToZip.getName(), zipOut, everyFile);
 } catch (IOException e) {
  LOGGER.warning(e);
 }

 LOGGER.info("压缩完成,耗时:{0}ms,保存在{1}", System.currentTimeMillis() - start, saveZip);
 }

 /**
 * 内部的压缩方法
 * 
 * @param toZip   要压缩的目录或文件
 * @param fileName ZIP 内的文件名
 * @param zipOut  ZIP 流
 * @param everyFile 输入 File,可在这 Lambda 里面判断是否加入 ZIP 压缩,返回 true 表示允许,反之不行
 */
 private static void zip(File toZip, String fileName, ZipOutputStream zipOut, Function<File, Boolean> everyFile) {
 if (toZip.isHidden())
  return;

 if (everyFile != null && !everyFile.apply(toZip)) {
  return; // 跳过不要的
 }

 try {
  if (toZip.isDirectory()) {
  zipOut.putNextEntry(new ZipEntry(fileName.endsWith("/") ? fileName : fileName + "/"));
  zipOut.closeEntry();

  File[] children = toZip.listFiles();
  for (File childFile : children) {
   zip(childFile, fileName + "/" + childFile.getName(), zipOut, everyFile);
  }

  return;
  }

  zipOut.putNextEntry(new ZipEntry(fileName));

  try (FileInputStream in = new FileInputStream(toZip);) {
  IoHelper.write(in, zipOut, false);
  }
 } catch (IOException e) {
  LOGGER.warning(e);
 }
 }
}

到此这篇关于Java8 Zip 压缩与解压缩的实现的文章就介绍到这了,更多相关Java8 Zip 压缩与解压缩内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • SpringBoot集成Swagger2构建在线API文档的代码详解

    SpringBoot集成Swagger2构建在线API文档的代码详解

    这篇文章主要介绍了SpringBoot集成Swagger2构建在线API文档,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-12-12
  • Spring Boot搭建文件上传服务的方法

    Spring Boot搭建文件上传服务的方法

    这篇文章主要为大家详细介绍了Spring Boot搭建文件上传服务的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-11-11
  • Prometheus pushgateway的使用详解

    Prometheus pushgateway的使用详解

    为了防止 pushgateway 重启或意外挂掉,导致数据丢失,我们可以通过 -persistence.file 和 -persistence.interval 参数将数据持久化下来,接下来通过本文给大家介绍下Prometheus pushgateway的使用,感兴趣的朋友一起看看吧
    2021-11-11
  • Spring Boot源码实现StopWatch优雅统计耗时

    Spring Boot源码实现StopWatch优雅统计耗时

    这篇文章主要为大家介绍了Spring Boot源码实现StopWatch优雅统计耗时,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-07-07
  • Flutter实现文本组件、图标及按钮组件的代码

    Flutter实现文本组件、图标及按钮组件的代码

    这篇文章主要介绍了Flutter实现文本组件、图标及按钮组件的代码,本文给大家介绍的非常详细,具有一定的参考借鉴价值 ,需要的朋友可以参考下
    2019-07-07
  • Intellij IDEA Debug调试技巧(小结)

    Intellij IDEA Debug调试技巧(小结)

    这篇文章主要介绍了Intellij IDEA Debug调试技巧(小结),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-10-10
  • Springboot如何配置多个Redis数据源(非集群)

    Springboot如何配置多个Redis数据源(非集群)

    这篇文章主要介绍了Springboot如何配置多个Redis数据源(非集群)方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2025-03-03
  • 详解 Java中日期数据类型的处理之格式转换的实例

    详解 Java中日期数据类型的处理之格式转换的实例

    这篇文章主要介绍了详解 Java中日期数据类型的处理之格式转换的实例的相关资料,日期以及时间格式处理,在Java中时间格式一般会涉及到的数据类型包括Calendar类和Date类,需要的朋友可以参考下
    2017-08-08
  • SpringBoot处理请求参数中包含特殊符号

    SpringBoot处理请求参数中包含特殊符号

    今天写代码遇到了一个问题,请求参数是个路径“D:/ExcelFile”,本文就详细的介绍一下该错误的解决方法,感兴趣的可以了解一下
    2021-06-06
  • Java Arrays工具类用法详解

    Java Arrays工具类用法详解

    这篇文章主要介绍了Java Arrays工具类用法,结合实例形式分析了java Arrays工具类针对数组元素修改、复制、排序等操作使用技巧与相关注意事项,需要的朋友可以参考下
    2019-05-05

最新评论