递归实现文件夹及文件夹下文件的zip打包

**

递归实现文件夹及文件夹下文件的zip打包

**

直接上代码

zip打包需要的依赖pom文件:

  <!--https://mvnrepository.com/artifact/jcifs/jcifs -->
  <dependency>
    <groupId>jcifs</groupId>
    <artifactId>jcifs</artifactId>
    <version>1.3.17</version>
  </dependency>
  <!-- 压缩zip包需要的依赖 -->
  <dependency>
    <groupId>ant</groupId>
    <artifactId>ant</artifactId>
    <version>1.6.5</version>
  </dependency>

创建zip文件

/**
   * 创建ZIP文件
   *
   * @param sourcePath 文件或文件夹路径
   * @param zipPath 生成的zip文件存在路径(包括文件名)
   * @param isDrop 是否删除原文件:true删除、false不删除
   */
  public static void createZip(String sourcePath, String zipPath, Boolean isDrop) {
    FileOutputStream fos = null;
    ZipOutputStream zos = null;
    try {
      fos = new FileOutputStream(zipPath);
      zos = new ZipOutputStream(fos);
      //此处修改字节码方式。
      zos.setEncoding("gbk");
      writeZip(new File(sourcePath), "", zos, isDrop);
    } catch (FileNotFoundException e) {
      log.error("创建ZIP文件失败", e);
    } finally {
      try {
        if (zos != null) {
          zos.close();
        }
        if(fos != null){
          fos.close();
        }
      } catch (IOException e) {
        log.error("创建ZIP文件失败", e);
      }

    }
  }

实现文件夹的zip打包

/**
   * 递归实现文件夹及文件夹下文件的zip打包
   * */
  private static void writeZip(File file, String parentPath, ZipOutputStream zos, Boolean isDrop) {
    // 需要压缩的文件夹是否存在
    if (file.exists()) {
      // 处理文件夹
      if (file.isDirectory()) {
        // 文件夹名称 + "/"
        parentPath += file.getName() + File.separator;
        System.out.println(parentPath);
        // 获取文件夹下的文件夹或文件
        File[] files = file.listFiles();
        System.out.println("sss: " + files);
        if (files.length != 0) {
          for (File f : files) {
            writeZip(f, parentPath, zos, isDrop);
          }
        } else {
          // 空目录则创建当前目录
          try {
            zos.putNextEntry(new ZipEntry(parentPath));
          } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        }
      } else {
        FileInputStream fis = null;
        try {
          fis = new FileInputStream(file);
          ZipEntry ze = new ZipEntry(parentPath + file.getName());
          zos.putNextEntry(ze);
          byte[] content = new byte[1024];
          int len;
          while ((len = fis.read(content)) != -1) {
            zos.write(content, 0, len);
            zos.flush();
          }

        } catch (Exception e) {
          log.error("创建ZIP文件失败", e);
        }
        finally {
          try {
            if (fis != null) {
              fis.close();
            }
            if (isDrop) {
              clean(file);
            }
          } catch (IOException e) {
            log.error("创建ZIP文件失败", e);
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      }
    }
  }

清空原文件或文件夹

/**
   * 清空文件和文件目录
   */
  public static void clean(File f) throws Exception {
    String cs[] = f.list();
    if (cs == null || cs.length <= 0) {
      System.out.println("delFile:[ " + f + " ]");
      boolean isDelete = f.delete();
      if (!isDelete) {
        System.out.println("delFile:[ " + f.getName() + "文件删除失败!" + " ]");
        throw new Exception(f.getName() + "文件删除失败!");
      }
    } else {
      for (int i = 0; i < cs.length; i++) {
        String cn = cs[i];
        String cp = f.getPath() + File.separator + cn;
        File f2 = new File(cp);
        if (f2.exists() && f2.isFile()) {
          System.out.println("delFile:[ " + f2 + " ]");
          boolean isDelete = f2.delete();
          if (!isDelete) {
            System.out.println("delFile:[ " + f2.getName() + "文件删除失败!" + " ]");
            throw new Exception(f2.getName() + "文件删除失败!");
          }
        } else if (f2.exists() && f2.isDirectory()) {
          clean(f2);
        }
      }
      System.out.println("delFile:[ " + f + " ]");
      boolean isDelete = f.delete();
      if (!isDelete) {
        System.out.println("delFile:[ " + f.getName() + "文件删除失败!" + " ]");
        throw new Exception(f.getName() + "文件删除失败!");
      }
    }
  }

测试主方法

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
	测试方法
*/
public static void main(String[] args) {
    System.out.println(new Date().toString());
    Date d = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("HHmm-ss");
    System.out.println(sdf.format(d));
    ArrayList<String> listFileName = new ArrayList<String>();
    try {
      createZip("F://DownloadImgs/a", "g://DownloadImgs/ce.zip", false);
      // 返回文件写入路径
      System.out.println("F://DownloadImgs/+YWH");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }.

注意

在下载的zip包必须和原文件夹区分位置,可以在一个盘符下,但是必须在不同的文件夹下,最好是两个盘符下,不然会发生递归死循环。

暂做一个小笔记,希望能帮到需要的。代码中有什么错误,或者更好的实现方式,可以指出,共同进步。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值