ZipOutputStream压缩相关记录

import org.apache.commons.io.IOUtils;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
public static void main(String[] args) {
//压缩后的文件存放地址及文件名称
ZipOutputStream zip = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream("D:\\test.zip")));
try {
 
//查找resources文件下mapper/knowledge文件夹位置
   String patch = Thread.currentThread().getContextClassLoader().getResource("").getPath() + "mapper/knowledge";
   System.out.println(patch);
   File sourceFile = new File(patch);
   //是否文件
   if (sourceFile.isFile()) {
      toZip(sourceFile, zip, "");
   } else {
      fileToZip(sourceFile, zip, "");
   }
   zip.closeEntry();
} catch (
      Exception e) {
   e.printStackTrace();
}
//必须要关闭流
IOUtils.closeQuietly(zip);
}
/**
 * 压缩文件夹
 *
 * @param file       源文件
 * @param zip        压缩文件路径
 * @param targetPath 目录位置
 * @throws Exception 异常
 */
private static void fileToZip(File file, ZipOutputStream zip,String targetPath)throws Exception{
    //文件地址
    String fileName =  file.getName();
  targetPath +=fileName+File.separator;
  //插入目录
  ZipEntry entry  =new ZipEntry(targetPath);
  zip.putNextEntry(entry);
  zip.closeEntry();

  if(file.listFiles() == null||file.listFiles().length==0)return;
  //读取文件夹下面所有目录
  File[] fileLists= file.listFiles();
  //逐个循环
  for (File fileList : fileLists) {
    //是否是文件夹
      if(!fileList.isDirectory()){
        //插入文件
        toZip(fileList,zip,targetPath);
      }else {
        fileToZip(fileList,zip,targetPath);
      }
  }
}

/**
 * 插入文件
 * @param file 文件file
 * @param zip   输出zip
 * @param targetPath 目录位置
 * @throws Exception 异常
 */
private static void toZip(File file, ZipOutputStream zip,String targetPath ) throws Exception {
    //文件位置
  ZipEntry entry = new ZipEntry(targetPath + file.getName());
    byte[] buf = new byte[1024];
    zip.putNextEntry(entry);
    //流的方式插入zip
    InputStream read = new FileInputStream(file);
    int ch = -1;
    while ((ch = read.read(buf)) != -1) {
      zip.write(buf, 0, ch);
    }
    read.close();
    zip.closeEntry();

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值