可实现: 文件、文件夹的解压缩操作

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;/*** 文件压缩工具类*/
public class ZipUtil {private static final int BUFFER_SIZE = 2 * 1024;/*** 是否保留原来的目录结构* true:  保留目录结构;* false: 所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)*/private static final boolean KeepDirStructure = true;private static final Logger log = LoggerFactory.getLogger(ZipUtil.class);public static void main(String[] args) {try {toZip("E:/app1", "E:/app.zip",true);} catch (Exception e) {e.printStackTrace();}}/*** 压缩成ZIP* @param srcDir         压缩 文件/文件夹 路径* @param outPathFile    压缩 文件/文件夹 输出路径+文件名 D:/xx.zip* @param isDelSrcFile   是否删除原文件: 压缩前文件*/public static void toZip(String srcDir, String outPathFile,boolean isDelSrcFile) throws Exception {long start = System.currentTimeMillis();FileOutputStream out = null; ZipOutputStream zos = null;try {out = new FileOutputStream(new File(outPathFile));zos = new ZipOutputStream(out);File sourceFile = new File(srcDir);if(!sourceFile.exists()){throw new Exception("需压缩文件或者文件夹不存在");}compress(sourceFile, zos, sourceFile.getName());if(isDelSrcFile){delDir(srcDir);}log.info("原文件:{}. 压缩到:{}完成. 是否删除原文件:{}. 耗时:{}ms. ",srcDir,outPathFile,isDelSrcFile,System.currentTimeMillis()-start);} catch (Exception e) {log.error("zip error from ZipUtils: {}. ",e.getMessage());throw new Exception("zip error from ZipUtils");} finally {try {if (zos != null) {zos.close();}if (out != null) {out.close();}} catch (Exception e) {}}}/*** 递归压缩方法* @param sourceFile 源文件* @param zos zip输出流* @param name 压缩后的名称*/private static void compress(File sourceFile, ZipOutputStream zos, String name)throws Exception {byte[] buf = new byte[BUFFER_SIZE];if (sourceFile.isFile()) {zos.putNextEntry(new ZipEntry(name));int len;FileInputStream in = new FileInputStream(sourceFile);while ((len = in.read(buf)) != -1) {zos.write(buf, 0, len);}zos.closeEntry();in.close();} else {File[] listFiles = sourceFile.listFiles();if (listFiles == null || listFiles.length == 0) {if (KeepDirStructure) {zos.putNextEntry(new ZipEntry(name + "/"));zos.closeEntry();}} else {for (File file : listFiles) {if (KeepDirStructure) {compress(file, zos, name + "/" + file.getName());} else {compress(file, zos, file.getName());}}}}}/*** 解压文件到指定目录*/@SuppressWarnings({ "rawtypes", "resource" })public static void unZipFiles(String zipPath, String descDir) throws IOException {log.info("文件:{}. 解压路径:{}. 解压开始.",zipPath,descDir);long start = System.currentTimeMillis();try{File zipFile = new File(zipPath);System.err.println(zipFile.getName());if(!zipFile.exists()){throw new IOException("需解压文件不存在.");}File pathFile = new File(descDir);if (!pathFile.exists()) {pathFile.mkdirs();}ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"));for (Enumeration entries = zip.entries(); entries.hasMoreElements();) {ZipEntry entry = (ZipEntry) entries.nextElement();String zipEntryName = entry.getName();System.err.println(zipEntryName);InputStream in = zip.getInputStream(entry);String outPath = (descDir + File.separator + zipEntryName).replaceAll("\\*", "/");System.err.println(outPath);// 判断路径是否存在,不存在则创建文件路径File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));if (!file.exists()) {file.mkdirs();}// 判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压if (new File(outPath).isDirectory()) {continue;}// 输出文件路径信息OutputStream out = new FileOutputStream(outPath);byte[] buf1 = new byte[1024];int len;while ((len = in.read(buf1)) > 0) {out.write(buf1, 0, len);}in.close();out.close();}log.info("文件:{}. 解压路径:{}. 解压完成. 耗时:{}ms. ",zipPath,descDir,System.currentTimeMillis()-start);}catch(Exception e){log.info("文件:{}. 解压路径:{}. 解压异常:{}. 耗时:{}ms. ",zipPath,descDir,e,System.currentTimeMillis()-start);throw new IOException(e);}}// 删除文件或文件夹以及文件夹下所有文件public static void delDir(String dirPath) throws IOException {log.info("删除文件开始:{}.",dirPath);long start = System.currentTimeMillis();try{File dirFile = new File(dirPath);if (!dirFile.exists()) {return;}if (dirFile.isFile()) {dirFile.delete();return;}File[] files = dirFile.listFiles();if(files==null){return;}for (int i = 0; i < files.length; i++) {delDir(files[i].toString());}dirFile.delete();log.info("删除文件:{}. 耗时:{}ms. ",dirPath,System.currentTimeMillis()-start);}catch(Exception e){log.info("删除文件:{}. 异常:{}. 耗时:{}ms. ",dirPath,e,System.currentTimeMillis()-start);throw new IOException("删除文件异常.");}}
}

Java基础-实现zip解压缩相关推荐

  1. 【java基础】zip压缩文件

    2019独角兽企业重金招聘Python工程师标准>>> 1.代码片段 public static boolean fileToZip(String sourceFilePath, S ...

  2. Java基础(二):集合、IO流(Zip压缩输入/输出流等)、File文件类、反射、枚举

    Java基础(一):编译和解释.数据类型.变量作用域.String常用方法.数组.面向对象.异常 Java基础(二):集合.IO流(Zip压缩输入/输出流等).File文件类.反射.枚举 Java异常 ...

  3. java 压缩技术_Java压缩技术(三) ZIP解压缩——Java原生实现

    JavaEye的朋友跟我说:"你一口气把ZIP压缩和解压缩都写到一个帖子里,我看起来很累,不如分开好阅读".ok,面向读者需求,我做调整,这里单说ZIP解压缩! 相关链接: Jav ...

  4. java 删除压缩zip文件_从ZIP存档中删除文件,而无需在Java或Python中解压缩 - java...

    从ZIP存档中删除文件,而无需使用Java(首选)或Python解压缩 你好 我使用包含数百个高度压缩的文本文件的大型ZIP文件.解压缩ZIP文件时,可能要花一些时间,并且很容易消耗多达20 GB的磁 ...

  5. Java压缩技术(三) ZIP解压缩——Java原生实现

    转载自   Java压缩技术(三) ZIP解压缩--Java原生实现 解压缩与压缩运作方式相反,原理大抵相同,由ZipInputStream通过read方法对数据解压,同时需要通过CheckedInp ...

  6. java.util.zip_[Java 基础] 使用java.util.zip包压缩和解压缩文件

    Java API中的import java.util.zip.*;包下包含了Java对于压缩文件的所有相关操作. 我们可以使用该包中的方法,结合IO中的相关知识,进行文件的压缩和解压缩相关操作. Zi ...

  7. android zip解压缩

    android  zip解压缩 public class ZipUtils {public ZipUtils() {} /* 以输入流的形式解压 */public static void UnZipF ...

  8. java基础知识-对象和类

    前言: 因为要准备Java面试,所有将java基础知识点重新复习一遍,主要笔记来源于菜鸟教程和java核心技术的书籍中,也有一些博客上的资料(这些只供我个人学习使用) Java 对象和类 对象:对象是 ...

  9. JAVA——GZIP压缩与解压缩

    基本概念 GZIP编码:GZIP最早由Jean-loup Gailly和Mark Adler创建,用于UNⅨ系统的文件压缩.我们在Linux中经常会用到后缀为.gz的文件,它们就是GZIP格式的.现今 ...

最新文章

  1. linux tty core code,linux tty core 源码分析(5)
  2. 【Java】实战Java虚拟机之五“开启JIT编译”
  3. Hibernate之N+1问题
  4. 戴尔笔记本win8全新安装
  5. android 解决错误:Intel HAXM is required to run this AVD
  6. art-template 入门(二)之安装
  7. 读小米的《参与感》书的摘录(一),与大家分享!
  8. 计算机专业在湖南录取分数,计算机科学与技术专业分数线各大学排名(湖南)
  9. 计算机tpm管理,TPM管理工厂实施TPM可能面临的陷阱
  10. matlab中geoshow函数的使用/属性设置
  11. Flutter 蓝牙便携打印插件
  12. gulp4.0的坑:提示: Error: watching index.html: watch task has to be a function (optionally generated by u
  13. html css齿轮滚动特效,纯CSS3实现的齿轮滚动动画
  14. 大陆二代居民身份证校验代码
  15. 如何安装SPSS软件
  16. Arcgis水文分析模块小流域划分流程
  17. 基于三维时空卷积网络的自监督点云预测(CoRL2021)
  18. 计算机无法安装蓝牙设备,如果蓝牙耳机已连接到计算机并且无法安装设备驱动程序,该怎么办...
  19. 网页静态化之Freemarker
  20. 修改UA标识,解除校园网同类设备的数量限制

热门文章

  1. 双系统装完只能u盘启动_双系统引导失败如何修复教程?用NTBootAutofix一键修复...
  2. BoundingBox 图片分割
  3. Android 笔记 沉浸式状态栏设置及效果说明
  4. 求1000的阶乘尾部0的个数
  5. PyQt5 基本窗口控件(状态栏/窗口/图标/提示消息/QLabel/文本类控件)
  6. 中国矿产资源产业规划与投资前景预测分析报告2022-2027年
  7. 泰安学业水平考试计算机试卷,山东省泰安市2020年初中物理学业水平考试试题【含答案】...
  8. 竞猜类游戏Fastwin遭黑客攻击背后:Block.one官方悄然做了重大更新
  9. 密码计算机手机版,手机密码软件
  10. 百度智能云携手领悦助力宝马中国数字化转型