首页 > 编程语言 >java实现压缩zip包

java实现压缩zip包

时间:2022-08-25 18:33:58浏览次数:72  
标签:java zip 压缩 zos File new

  1 package com.common.util;
  2 
  3 import java.io.File;
  4 
  5 import java.io.FileInputStream;
  6 
  7 import java.io.FileOutputStream;
  8 
  9 import java.io.IOException;
 10 
 11 import java.io.OutputStream;
 12 
 13 import java.util.ArrayList;
 14 
 15 import java.util.List;
 16 
 17 import java.util.zip.ZipEntry;
 18 
 19 import java.util.zip.ZipOutputStream;
 20 
 21 
 22 
 23 public class ZipUtils {
 24 
 25 
 26 
 27     private static final int  BUFFER_SIZE = 2 * 1024;
 28 
 29     /**
 30 
 31      * 压缩成ZIP 方法1
 32 
 33      * @param srcDir 压缩文件夹路径
 34 
 35      * @param out    压缩文件输出流
 36 
 37      * @param KeepDirStructure  是否保留原来的目录结构,true:保留目录结构;
 38 
 39      *                          false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
 40 
 41      * @throws RuntimeException 压缩失败会抛出运行时异常
 42 
 43      */
 44 
 45     public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure)
 46             throws RuntimeException{
 47 
 48 
 49 
 50         long start = System.currentTimeMillis();
 51 
 52         ZipOutputStream zos = null ;
 53 
 54         try {
 55 
 56             zos = new ZipOutputStream(out);
 57 
 58             File sourceFile = new File(srcDir);
 59 
 60             compress(sourceFile,zos,sourceFile.getName(),KeepDirStructure);
 61 
 62             long end = System.currentTimeMillis();
 63 
 64             System.out.println("压缩完成,耗时:" + (end - start) +" ms");
 65 
 66         } catch (Exception e) {
 67 
 68             throw new RuntimeException("zip error from ZipUtils",e);
 69 
 70         }finally{
 71 
 72             if(zos != null){
 73 
 74                 try {
 75 
 76                     zos.close();
 77 
 78                 } catch (IOException e) {
 79 
 80                     e.printStackTrace();
 81 
 82                 }
 83 
 84             }
 85 
 86         }
 87 
 88 
 89 
 90     }
 91 
 92 
 93 
 94     /**
 95 
 96      * 压缩成ZIP 方法2
 97 
 98      * @param srcFiles 需要压缩的文件列表
 99 
100      * @param out           压缩文件输出流
101 
102      * @throws RuntimeException 压缩失败会抛出运行时异常
103 
104      */
105 
106     public static void toZip(List<File> srcFiles , OutputStream out)throws RuntimeException {
107 
108         long start = System.currentTimeMillis();
109 
110         ZipOutputStream zos = null ;
111 
112         try {
113 
114             zos = new ZipOutputStream(out);
115 
116             for (File srcFile : srcFiles) {
117 
118                 byte[] buf = new byte[BUFFER_SIZE];
119 
120                 zos.putNextEntry(new ZipEntry(srcFile.getName()));
121 
122                 int len;
123 
124                 FileInputStream in = new FileInputStream(srcFile);
125 
126                 while ((len = in.read(buf)) != -1){
127 
128                     zos.write(buf, 0, len);
129 
130                 }
131 
132                 zos.closeEntry();
133 
134                 in.close();
135 
136             }
137 
138             long end = System.currentTimeMillis();
139 
140             System.out.println("压缩完成,耗时:" + (end - start) +" ms");
141 
142         } catch (Exception e) {
143 
144             throw new RuntimeException("zip error from ZipUtils",e);
145 
146         }finally{
147 
148             if(zos != null){
149 
150                 try {
151 
152                     zos.close();
153 
154                 } catch (IOException e) {
155 
156                     e.printStackTrace();
157 
158                 }
159 
160             }
161 
162         }
163 
164     }
165 
166 
167 
168 
169 
170     /**
171 
172      * 递归压缩方法
173 
174      * @param sourceFile 源文件
175 
176      * @param zos        zip输出流
177 
178      * @param name       压缩后的名称
179 
180      * @param KeepDirStructure  是否保留原来的目录结构,true:保留目录结构;
181 
182      *                          false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
183 
184      * @throws Exception
185 
186      */
187 
188     private static void compress(File sourceFile, ZipOutputStream zos, String name,
189 
190                                  boolean KeepDirStructure) throws Exception{
191 
192         byte[] buf = new byte[BUFFER_SIZE];
193 
194         if(sourceFile.isFile()){
195 
196             // 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
197 
198             zos.putNextEntry(new ZipEntry(name));
199 
200             // copy文件到zip输出流中
201 
202             int len;
203 
204             FileInputStream in = new FileInputStream(sourceFile);
205 
206             while ((len = in.read(buf)) != -1){
207 
208                 zos.write(buf, 0, len);
209 
210             }
211 
212             // Complete the entry
213 
214             zos.closeEntry();
215 
216             in.close();
217 
218         } else {
219 
220             File[] listFiles = sourceFile.listFiles();
221 
222             if(listFiles == null || listFiles.length == 0){
223 
224                 // 需要保留原来的文件结构时,需要对空文件夹进行处理
225 
226                 if(KeepDirStructure){
227 
228                     // 空文件夹的处理
229 
230                     zos.putNextEntry(new ZipEntry(name + "/"));
231 
232                     // 没有文件,不需要文件的copy
233 
234                     zos.closeEntry();
235 
236                 }
237 
238 
239 
240             }else {
241 
242                 for (File file : listFiles) {
243 
244                     // 判断是否需要保留原来的文件结构
245 
246                     if (KeepDirStructure) {
247 
248                         // 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,
249 
250                         // 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了
251 
252                         compress(file, zos, name + "/" + file.getName(),KeepDirStructure);
253 
254                     } else {
255 
256                         compress(file, zos, file.getName(),KeepDirStructure);
257 
258                     }
259 
260 
261 
262                 }
263 
264             }
265 
266         }
267 
268     }
269 
270     public static void main(String[] args) throws Exception {
271 
272         /** 测试压缩方法1  */
273 
274         FileOutputStream fos1 = new FileOutputStream(new File("d:/in/mytest01.zip"));
275 
276         ZipUtils.toZip("D:/in/Michelin", fos1,true);
277 
278         /** 测试压缩方法2  */
279 
280         List<File> fileList = new ArrayList<>();
281 
282         fileList.add(new File("D:/Java/jdk1.7.0_45_64bit/bin/jar.exe"));
283 
284         fileList.add(new File("D:/Java/jdk1.7.0_45_64bit/bin/java.exe"));
285 
286         FileOutputStream fos2 = new FileOutputStream(new File("c:/mytest02.zip"));
287 
288         ZipUtils.toZip(fileList, fos2);
289 
290     }
291 
292 }

 

标签:java,zip,压缩,zos,File,new
From: https://www.cnblogs.com/lychee-wang/p/16625332.html

相关文章

  • Java Servlet 入门:问题系列:反射方法参数名获取不到问题:arg0,arg1
    问题:获取反射的方法参数名时,得到arg0,arg1,而不是定义的参数名。示例代码:Parameter[]parameters=methodInfo.getParameters();if(parameters!=null&&parame......
  • tqdm和zip组合使用时无法显示进度条-解决办法
    问题单独对于可迭代对象iterator使用tqdm时,结合循环就可以在终端显示进度条,以直观展示程序进度,如下:fromtqdmimporttqdmtextlist=[]foriinrange(10):te......
  • java下载word文档docx
    原文链接:https://blog.csdn.net/m0_51496483/article/details/122124567普通的下载功能,不过依然有一个值得关注的重要点……请看到最后!***HTML***按钮就不上了,你开心设计......
  • 图文详解 Java 泛型,写得太好了!
    泛型——一种可以接收数据类型的数据类型,本文将通俗讲解Java泛型的优点、方法及相关细节。一、泛型的引入我们都知道,继承是面向对象的三大特性之一,比如在我们向集合中......
  • 你真的了解java的泛型吗?
    1.java可以声明泛型数组吗?​ 我们都知道在java中声明一个普通数组,但是你知道如何声明一个泛型数组吗?​ 先来看一个简单的例子,Animals是Cat的父类,思考下Animals[]和Cat[......
  • java操作selenium浏览器自动化操作
    seleniumgithubselenium官网各类型浏览器webDriver驱动下载chrome浏览器webDriver驱动下载,注意要与电脑上实际安装的浏览器版本相对应原理说明:java代码直接通过sele......
  • Caused by: java.lang.UnsupportedClassVersionError: com/hfplm/handler/HFEBOMation
    Causedby:java.lang.UnsupportedClassVersionError:com/hfplm/handler/HFEBOMationHandlerhasbeencompiledbyamorerecentversionoftheJavaRuntime(classf......
  • Java 连接 MySQL
    让Java和MySQL连接起来-囧雪诺-博客园 https://www.cnblogs.com/jonsnow/p/6246131.htmlJava连接MySQL需要驱动包,可以下载菜鸟教程提供的 jar包:http://stati......
  • 【Java】LambdaStream
    JavaLambdaStreamFactoryimportjava.util.*;importjava.util.stream.*;publicclassLambdaStream{publicstatic<T>Stream<T>of(Spliterator<T>split......
  • Java生成带logo的二维码,并将二维码添加到图片中
    1.pom.xml<!--生成二维码--><dependency><groupId>cn.hutool</groupId><artifactId>hutool-extra</artifactId><version>5.4.3</version></dependency><d......