zoukankan      html  css  js  c++  java
  • java zip压缩文件和文件夹

    public class FileUtil {
    /**
    * 压缩文件-File
    * @param out zip流
    * @param srcFiles 要压缩的文件
    * @param path 相对路径
    * @param isParent 是否包含父路径: true包含,false不包含
    * @throws IOException
    */
    public static void ZipFiles(ZipOutputStream out, File srcFiles, String path, boolean isParent) throws IOException {
      path = path.replaceAll("\*", "/");
      byte[] buf = new byte[1024];
      if (srcFiles.isDirectory()) {
        File[] files = srcFiles.listFiles();
        String srcPath = srcFiles.getName();
        srcPath = srcPath.replaceAll("\*", "/");
        if (!srcPath.endsWith("/")) {
          srcPath += "/";
        }
        out.putNextEntry(new ZipEntry(path + srcPath));
        for (int i = 0; i < files.length; i++) {
          System.out.println(files[i].getParent());
          ZipFiles(out, files[i], path + srcPath, isParent);
        }
      } else {
        if (isParent) {
          String parentPath = srcFiles.getParent();
          int index = parentPath.lastIndexOf("\");
          String parentName = parentPath.substring(index + 1);
          path = parentName + "\";
        }
        FileInputStream in = new FileInputStream(srcFiles);
        out.putNextEntry(new ZipEntry(path + srcFiles.getName()));
        int len;
        while ((len = in.read(buf)) > 0) {
          out.write(buf, 0, len);
        }
        out.closeEntry();
        in.close();
      }
      }
    }

    测试例子

    public static void main(String[] args) throws IOException {
    ZipOutputStream zip = new ZipOutputStream(new FileOutputStream("D:\test\shaomch.zip"));
    File file1 = new File("D:\test\classPath.txt");
    FileUtil.ZipFiles(zip, file1, "", false);
    File file2 = new File("D:\test\name.txt");
    FileUtil.ZipFiles(zip, file2, "", false);
    File file3 = new File("D:\test\shao\3\0302移动端升级功能验证.xlsx");
    FileUtil.ZipFiles(zip, file3, "", true);
    zip.close();
    }

  • 相关阅读:
    【arc072f】AtCoder Regular Contest 072 F
    maven settings解决下载不了依赖包问题
    git 命令提交本地代码到新创建的仓库
    JAVA 利用切面、注解 动态判断请求信息中字段是否需要为空
    JAVA 根据身份证号码解析出生日期、性别、年龄
    利用JAVA正则快速获取URL的文件名
    datalist
    Mybatis map接收list参数
    bootstrap-table 列宽动态拖拽改变宽度
    JAVA 枚举类遍历与switch使用
  • 原文地址:https://www.cnblogs.com/michaelShao/p/6548608.html
Copyright © 2011-2022 走看看