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();
    }

  • 相关阅读:
    第一节 2字符串 简单
    第一节 1C#基础 简单
    终于找到wamp修改密码方式了!
    js通过class name获得元素
    JavaScript中arguments
    对技术的态度
    C++的坑真的多吗?
    js 常用正则
    js利用Array.splice实现Array的insert/remove
    c# asp.net webform web页面打印,可以控制需要打印和不需要打印的位置
  • 原文地址:https://www.cnblogs.com/michaelShao/p/6548608.html
Copyright © 2011-2022 走看看