ZIP解压缩文件的工具类【支持多级目录|全】

作者:Vashon

网上有很多的加压缩示例代码,但是都只是支持一级目录的操作,如果存在多级目录的话就不行了。本解压缩工具类经过多次检查及重构,最终分享给大家。

  1. package com.ywx.ziputils;
  2.  
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.FileNotFoundException;
  6. import java.io.FileOutputStream;
  7. import java.io.IOException;
  8. import java.io.InputStream;
  9. import java.io.OutputStream;
  10. import java.util.Enumeration;
  11. import java.util.zip.ZipEntry;
  12. import java.util.zip.ZipFile;
  13. import java.util.zip.ZipOutputStream;
  14.  
  15. /**
  16. * ZIP解压缩文件的工具类,文件可以是多级目录的结构进行解压,压缩操作.
  17. * @author yangwenxue(Vashon)
  18. *
  19. */
  20. public class ZipUtil {
  21. /**
  22. * 压缩文件操作
  23. * @param filePath 要压缩的文件路径
  24. * @param descDir 压缩文件的保存路径
  25. * @throws IOException
  26. */
  27. public static void zipFiles(String filePath,String descDir) throws IOException{
  28. ZipOutputStream zos=null;
  29. try {
  30. //创建一个zip输出流
  31. zos=new ZipOutputStream(new FileOutputStream(descDir));
  32. //启动压缩
  33. startZip(zos,"",filePath);
  34. System.out.println("=============压缩完毕=============");
  35. } catch (FileNotFoundException e) {
  36. //压缩失败,则删除创建的文件
  37. File zipFile=new File(descDir);
  38. if(zipFile.exists()){
  39. zipFile.delete();
  40. }
  41. e.printStackTrace();
  42. }finally{
  43. if(zos!=null){
  44. try {
  45. zos.close();
  46. } catch (IOException e) {
  47. e.printStackTrace();
  48. }
  49. }
  50. }
  51. }
  52. /**
  53. * 对目录中所有文件递归遍历进行压缩
  54. * @param zos 压缩输出流
  55. * @param oppositePath 在zip文件中的相对路径
  56. * @param filePath 要压缩的文件路径
  57. * @throws IOException
  58. */
  59. private static void startZip(ZipOutputStream zos, String oppositePath,
  60. String filePath) throws IOException {
  61. File file=new File(filePath);
  62. if(file.isDirectory()){//如果是压缩目录
  63. File[] files=file.listFiles();//列出所有目录
  64. for(int i=0;i<files.length;i++){
  65. File aFile=files[i];
  66. if(aFile.isDirectory()){//如果是目录,修改相对地址
  67. String newoppositePath=oppositePath+aFile.getName()+"/";
  68. //压缩目录,这是关键,创建一个目录的条目时,需要在目录名后面加多一个"/"
  69. ZipEntry entry=new ZipEntry(newoppositePath);
  70. zos.putNextEntry(entry);
  71. zos.closeEntry();
  72. startZip(zos, newoppositePath, aFile.getPath());
  73. }else{//如果不是目录,则进行压缩
  74. zipFile(zos,oppositePath,aFile);
  75. }
  76. }
  77. }else{//如果是压缩文件,直接调用压缩方法进行压缩
  78. zipFile(zos, oppositePath, file);
  79. }
  80. }
  81. /**
  82. * 压缩单个文件到目录中
  83. * @param zos zip输出流
  84. * @param oppositePath 在zip文件中的相对路径
  85. * @param file 要压缩的文件
  86. */
  87. private static void zipFile(ZipOutputStream zos, String oppositePath, File file) {
  88. //创建一个zip条目,每个zip条目都必须是相对于跟路径
  89. InputStream is=null;
  90.  
  91. try {
  92. ZipEntry entry=new ZipEntry(oppositePath+file.getName());
  93. //将条目保存到zip压缩文件当中
  94. zos.putNextEntry(entry);
  95. //从文件输入流当中读取数据,并将数据写到输出流当中
  96. is=new FileInputStream(file);
  97. //====这种压缩速度很快
  98. int length=0;
  99. int bufferSize=1024;
  100. byte[] buffer=new byte[bufferSize];
  101.  
  102. while((length=is.read(buffer, 0, bufferSize))>=0){
  103. zos.write(buffer, 0, length);
  104. }
  105.  
  106. //===============以下压缩速度很慢=================
  107. // int temp=0;
  108. //
  109. // while((temp=is.read())!=-1){
  110. // zos.write(temp);
  111. // }
  112. //==========================================
  113. zos.closeEntry();
  114. } catch (IOException e) {
  115. e.printStackTrace();
  116. }finally{
  117. if(is!=null){
  118. try {
  119. is.close();
  120. } catch (IOException e) {
  121. e.printStackTrace();
  122. }
  123. }
  124. }
  125. }
  126. /**
  127. * 解压文件操作
  128. * @param zipFilePath zip文件路径
  129. * @param descDir 解压出来的文件保存的目录
  130. */
  131. public static void unZiFiles(String zipFilePath,String descDir){
  132. File zipFile=new File(zipFilePath);
  133. File pathFile=new File(descDir);
  134.  
  135. if(!pathFile.exists()){
  136. pathFile.mkdirs();
  137. }
  138. ZipFile zip=null;
  139. InputStream in=null;
  140. OutputStream out=null;
  141.  
  142. try {
  143. zip=new ZipFile(zipFile);
  144. Enumeration<?> entries=zip.entries();
  145. while(entries.hasMoreElements()){
  146. ZipEntry entry=(ZipEntry) entries.nextElement();
  147. String zipEntryName=entry.getName();
  148. in=zip.getInputStream(entry);
  149.  
  150. String outPath=(descDir+"/"+zipEntryName).replace("\\*", "/");
  151. //判断路径是否存在,不存在则创建文件路径
  152. File file=new File(outPath.substring(0, outPath.lastIndexOf('/')));
  153. if(!file.exists()){
  154. file.mkdirs();
  155. }
  156. //判断文件全路径是否为文件夹,如果是上面已经创建,不需要解压
  157. if(new File(outPath).isDirectory()){
  158. continue;
  159. }
  160. out=new FileOutputStream(outPath);
  161.  
  162. byte[] buf=new byte[4*1024];
  163. int len;
  164. while((len=in.read(buf))>=0){
  165. out.write(buf, 0, len);
  166. }
  167. in.close();
  168.  
  169. System.out.println("==================解压完毕==================");
  170. }
  171. } catch (Exception e) {
  172. System.out.println("==================解压失败==================");
  173. e.printStackTrace();
  174. }finally{
  175. try {
  176. if(zip!=null){
  177. zip.close();
  178. }
  179. if(in!=null){
  180. in.close();
  181. }
  182. if(out!=null){
  183. out.close();
  184. }
  185. } catch (IOException e) {
  186. e.printStackTrace();
  187. }
  188. }
  189. }
  190. @SuppressWarnings("static-access")
  191. public static void main(String args[]) throws IOException{
  192. // long startTimes=System.currentTimeMillis();
  193. // new ZipUtil().zipFiles("f:"+File.separator+"Vashon2Xiaoai", "f:"+File.separator+"Vashon2Xiaoai_vvv.zip");
  194. // long times=System.currentTimeMillis()-startTimes;
  195. // System.out.println("耗时:"+times/1000+"秒");
  196. new ZipUtil().unZiFiles("f:"+File.separator+"Vashon2Xiaoai_vvv.zip", "f:"+File.separator+"vvvvss");
  197. }
  198. }

实践出真知,希望广大读者动手操作,如问题可以反馈,共同探讨。。。

版权声明:本文为博主原创文章,未经博主允许不得转载。

ZIP解压缩文件的工具类【支持多级目录|全】的更多相关文章

  1. ZIP解压缩文件的工具类【支持多级文件夹|全】

    ZIP解压缩文件的工具类[支持多级文件夹|全] 作者:Vashon 网上有非常多的加压缩演示样例代码.可是都仅仅是支持一级文件夹的操作.假设存在多级文件夹的话就不行了. 本解压缩工具类经过多次检查及重 ...

  2. java将文件打包成ZIP压缩文件的工具类实例

    package com.lanp; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import ja ...

  3. 文件类型工具类:FileTypeUtil

    个人学习,仅供参考! package com.example.administrator.filemanager.utils;import java.io.File;/** * 文件类型工具类 * * ...

  4. Android开发调试日志工具类[支持保存到SD卡]

    直接上代码: package com.example.callstatus; import java.io.File; import java.io.FileWriter; import java.i ...

  5. 写文件的工具类,输出有格式的文件(txt、json/csv)

    import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io. ...

  6. Java 文件切割工具类

    Story: 发送MongoDB 管理软件到公司邮箱,工作使用. 1.由于公司邮箱限制附件大小,大文件无法发送,故做此程序用于切割大文件成多个小文件,然后逐个发送. 2.收到小文件之后,再重新组合成原 ...

  7. Java 压缩文件夹工具类(包含解压)

    依赖jar <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons ...

  8. iOS开发拓展篇—封装音频文件播放工具类

    iOS开发拓展篇—封装音频文件播放工具类 一.简单说明 1.关于音乐播放的简单说明 (1)音乐播放用到一个叫做AVAudioPlayer的类 (2)AVAudioPlayer常用方法 加载音乐文件 - ...

  9. 文件夹工具类 - FolderUtils

    文件夹工具类,提供创建完整路径的方法. 源码如下:(点击下载 -FolderUtils.java .commons-io-2.4.jar ) import java.io.File; import o ...

随机推荐

  1. OpenCV——PS滤镜算法之 Ellipsoid (凸出)

    // define head function #ifndef PS_ALGORITHM_H_INCLUDED #define PS_ALGORITHM_H_INCLUDED #include < ...

  2. 机器学习 Hidden Markov Models 3

    Viterbi Algorithm 前面我们提到过,HMM的第二类问题是利用HMM模型和可观察序列寻找最有可能生成该观察序列的隐藏变量的序列.简单来说,第一类问题是通过模型计算生成观察序列的概率,而第 ...

  3. 「LuoguP3369」 【模板】普通平衡树 (用vector乱搞平衡树

    Description 您需要写一种数据结构(可参考题目标题),来维护一些数,其中需要提供以下操作: 插入 x 数 删除 x 数(若有多个相同的数,应只删除一个) 查询 x 数的排名(排名定义为比当前 ...

  4. Laravel 5 微信小程序扩展

    小程序官方的加解密 SDK 已经非常清楚了,只不过改成 Laravel 风格而已,仅仅相当于搬砖工.至于重复造轮子,我发现其他人的扩展解密用户信息的时候代码出错了,并且需要安装一个 Laravel 的 ...

  5. .NETFramework:Regex

    ylbtech-.NETFramework:Regex 1.返回顶部 1. #region 程序集 System, Version=4.0.0.0, Culture=neutral, PublicKe ...

  6. 关于spring boot在启动的时候报错: java.lang.Error: generate operation swagger failed, xxx.xxx.xxx

    Error starting ApplicationContext. To display the auto-configuration report re-run your application ...

  7. k8s-RBAC授权-十六

    一.简介 基于角色的访问控制(“RBAC”) http://docs.kubernetes.org.cn/80.html (1) Kubernetes的授权是基于插件形式的,常用的授权插件有以下几种: ...

  8. ASP.NET Core MVC 2.x 全面教程__ASP.NET Core MVC 19. XSS & CSRF

    存库之前先净化,净化之后再提交到数据库 刚才插入的那笔数据 把默认的Razor引擎默认的EnCode去掉.Razor默认会开启htmlEnCodding 数据恢复回来 插入数据库之前对插入的数据进行净 ...

  9. CentOS Linux自动备份MySQL数据库到远程FTP服务器并删除指定日期前的备份Shell脚本

    说明: 我这里要把MySQL数据库存放目录/var/lib/mysql下面的pw85数据库备份到/home/mysql_data里面,并且保存为mysqldata_bak_2011_11_03.tar ...

  10. TP3.2单字母函数

    A方法 A方法用于在内部实例化控制器 调用格式:A(‘[项目://][分组/]模块’,’控制器层名称’) 最简单的用法: $User = A('User'); 表示实例化当前项目的UserAction ...