今天开发应用需要使用到压缩文件功能,在网上查找了一下相关资料,发现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;
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
ps:代码里面使用的CCLog是自定义