zipWithPassword static method

Future<String> zipWithPassword(
  1. String sourcePath,
  2. String targetPath,
  3. String password
)

使用密码压缩文件/文件夹

sourcePath 源文件/文件夹路径

targetPath 目标zip文件路径

password 压缩密码

Implementation

static Future<String> zipWithPassword(
  String sourcePath,
  String targetPath,
  String password,
) async {
  try {
    final sourceDir = Directory(sourcePath);
    final archive = Archive();

    // 如果是目录,递归添加文件
    if (await sourceDir.exists()) {
      await for (final file in sourceDir.list(recursive: true)) {
        if (file is File) {
          final relativePath = file.path.substring(sourcePath.length);
          final data = await file.readAsBytes();
          archive.addFile(ArchiveFile(
            relativePath,
            data.length,
            data,
          ));
        }
      }
    }
    // 如果是单个文件
    else if (await File(sourcePath).exists()) {
      final file = File(sourcePath);
      final data = await file.readAsBytes();
      archive.addFile(ArchiveFile(
        file.path.split('/').last,
        data.length,
        data,
      ));
    } else {
      throw Exception('源文件/文件夹不存在');
    }

    // 使用密码压缩并保存
    final zipData = ZipEncoder(password: password).encode(archive);
    final zipFile = File(targetPath);
    await zipFile.writeAsBytes(zipData);
    await Future.delayed(const Duration(milliseconds: 100));
    return targetPath;
  } catch (e) {
    throw Exception('加密压缩错误: $e');
  }
}