java zip压缩文件和文件夹

时间:2023-03-09 04:12:26
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();
}