今天开发应用需要使用到压缩文件功能,在网上查找了一下相关资料,发现ZipArchive使用相对简单点,自己就写了个demo函数:
ZipArchive下载地址:https://code.google.com/p/ziparchive/
代码:
- +(NSString *)zipFiles:(NSArray *)paramFiles
- {
- //生成zip文件名字
- NSString * zipFileName = [[CUtils generateRndString] stringByAppendingPathExtension:@"zip"];
- //取得zip文件全路径
- NSString * zipPath = [[CUtils documentPath] stringByAppendingPathComponent:zipFileName];
- //判断文件是否存在,如果存在则删除文件
- NSFileManager * fileManager = [NSFileManager defaultManager];
- @try
- {
- if([fileManager fileExistsAtPath:zipPath])
- {
- if(![fileManager removeItemAtPath:zipPath error:nil])
- {
- CCLog(@"Delete zip file failure.");
- }
- }
- }
- @catch (NSException * exception) {
- CCLog(@"%@",exception);
- }
- //判断需要压缩的文件是否为空
- if(paramFiles == nil || [paramFiles count] == 0)
- {
- CCLog(@"The files want zip is nil.");
- return nil;
- }
- //实例化并创建zip文件
- ZipArchive * zipArchive = [[ZipArchive alloc] init];
- [zipArchive CreateZipFile2:zipPath];
- //遍历文件
- for(NSString * fileName in paramFiles)
- {
- NSString * filePath = [[CUtils documentPath] stringByAppendingPathComponent:fileName];
- if([fileManager fileExistsAtPath:filePath])
- { //添加文件到压缩文件
- [zipArchive addFileToZip:filePath newname:fileName];
- }
- }
- //关闭文件
- if([zipArchive CloseZipFile2])
- {
- CCLog(@"Create zip file success.");
- [zipArchive release];
- return zipPath;
- }
- [zipArchive release];
- return nil;
- }
ps:代码里面使用的CCLog是自定义