zipWithPassword static method
使用密码压缩文件/文件夹为 zip 包
sourcePath 源文件/文件夹路径
targetPath 输出 zip 文件路径
password 压缩密码
示例:
String zipFile = await ZipUtil.zipWithPassword('a.txt', 'a.enc.zip', '123456');
返回结果: String 返回生成的zip文件路径
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(Platform.pathSeparator).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');
}
}