当前位置:主页 > 移动开发 > Android代码 >

Android实现文件或文件夹压缩成.zip格式压缩包

时间:2021-09-12 14:00:29 | 栏目:Android代码 | 点击:

本文实例为大家分享了Android压缩文件和文件夹的方法,供大家参考,具体内容如下

 /**
   * 压缩文件和文件夹
   *
   * @param srcFileString 要压缩的文件或文件夹
   * @param zipFileString 压缩完成的Zip路径
   * @throws Exception
   */
  public static void ZipFolder(String srcFileString, String zipFileString) throws Exception {
    //创建ZIP
    ZipOutputStream outZip = new ZipOutputStream(new FileOutputStream(zipFileString));
    //创建文件
    File file = new File(srcFileString);
    //压缩
    LogUtils.LOGE("---->"+file.getParent()+"==="+file.getAbsolutePath());
    ZipFiles(file.getParent()+ File.separator, file.getName(), outZip);
    //完成和关闭
    outZip.finish();
    outZip.close();
  }
 
  /**
   * 压缩文件
   *
   * @param folderString
   * @param fileString
   * @param zipOutputSteam
   * @throws Exception
   */
  private static void ZipFiles(String folderString, String fileString, ZipOutputStream zipOutputSteam) throws Exception {
    LogUtils.LOGE("folderString:" + folderString + "\n" +
        "fileString:" + fileString + "\n==========================");
    if (zipOutputSteam == null)
      return;
    File file = new File(folderString + fileString);
    if (file.isFile()) {
      ZipEntry zipEntry = new ZipEntry(fileString);
      FileInputStream inputStream = new FileInputStream(file);
      zipOutputSteam.putNextEntry(zipEntry);
      int len;
      byte[] buffer = new byte[4096];
      while ((len = inputStream.read(buffer)) != -1) {
        zipOutputSteam.write(buffer, 0, len);
      }
      zipOutputSteam.closeEntry();
    } else {
      //文件夹
      String fileList[] = file.list();
      //没有子文件和压缩
      if (fileList.length <= 0) {
        ZipEntry zipEntry = new ZipEntry(fileString + File.separator);
        zipOutputSteam.putNextEntry(zipEntry);
        zipOutputSteam.closeEntry();
      }
      //子文件和递归
      for (int i = 0; i < fileList.length; i++) {
        ZipFiles(folderString+fileString+"/", fileList[i], zipOutputSteam);
      }
    }
}

您可能感兴趣的文章:

相关文章