java 压缩文件

 1   /**
 2      * @param source    待压缩文件/文件夹路径
 3      * @param destination   压缩后压缩文件路径
 4      * @return 压缩多个文件夹
 5      */
 6     public static boolean toZip(String source, String destination) {
 7         try {
 8             FileOutputStream out = new FileOutputStream(destination);
 9             ZipOutputStream zipOutputStream = new ZipOutputStream(out);
10             File sourceFile = new File(source);
11 
12             // 递归压缩文件夹
13             compress(sourceFile, zipOutputStream, sourceFile.getName());
14 
15             zipOutputStream.flush();
16             zipOutputStream.close();
17         } catch (IOException e) {
18             System.out.println("failed to zip compress, exception");
19             return false;
20         }
21         return true;
22     }
23 
24     private static void compress(File sourceFile, ZipOutputStream zos, String name) throws IOException {
25         byte[] buf = new byte[1024];
26         if(sourceFile.isFile()){
27             // 压缩单个文件,压缩后文件名为当前文件名
28             zos.putNextEntry(new ZipEntry(name));
29             // copy文件到zip输出流中
30             int len;
31             FileInputStream in = new FileInputStream(sourceFile);
32             while ((len = in.read(buf)) != -1){
33                 zos.write(buf, 0, len);
34             }
35             zos.closeEntry();
36             in.close();
37         } else {
38             File[] listFiles = sourceFile.listFiles();
39             if(listFiles == null || listFiles.length == 0){
40                 // 空文件夹的处理(创建一个空ZipEntry)
41                 zos.putNextEntry(new ZipEntry(name + "/"));
42                 zos.closeEntry();
43             }else {
44                 // 递归压缩文件夹下的文件
45                 for (File file : listFiles) {
46                     compress(file, zos, name + "/" + file.getName());
47                 }
48             }
49         }
50     }

 

posted @ 2023-01-30 16:00  一杯清茶一本书  阅读(69)  评论(0编辑  收藏  举报