zip static method
压缩文件/文件夹为zip包(不加密)
sourcePath 源文件/文件夹路径
targetPath 输出 zip 文件路径
示例:
String zipFile = await ZipUtil.zip('a.txt', 'a.zip');
返回结果: String 返回生成的zip文件路径
Implementation
static Future<String> zip(String sourcePath, String targetPath) 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().encode(archive);
final zipFile = File(targetPath);
await zipFile.writeAsBytes(zipData);
await Future.delayed(const Duration(milliseconds: 100));
return targetPath;
} catch (e) {
throw Exception('压缩错误: $e');
}
}