iOS 使用ZipArchive壓縮文件
ZipArchive* zipFile = [[ZipArchive alloc] init];
//次數得zipfilename需要一個完整得路徑,例如***/Documents/demo.zip
[zipFile CreateZipFile2:@"zipfilename"];
//有兩種可選得方式進行創建壓縮包,帶密碼和不帶密碼的
[[zipFile CreateZipFile2:@"zipfilename" Password:@"your password"];
//接下來就是將需要壓縮的文件添加到這個壓縮包中
//這里第一個參數需要完整的路徑,例如:***/Documents/a.txt newname是指文件在壓縮包中的名字,不需要路徑,只是一個名稱
[zipFile addFileToZip:@"fullpath of the file" newname:@"new name of the file without path"];
//如果需要將多個文件進行壓縮,即壓縮文件夾,重復addFileToZip方法即可
[zipFile CloseZipFile2];
[zipFile release];
//釋放內存
解壓zip包:
ZipArchive* zipFile = [[ZipArchive alloc] init];
[zipFile UnzipOpenFile:@"zip file name"];
//同樣,對應的就有兩種打開zip包的方式,帶密碼和不帶密碼
[zipFile UnzipOpenFile:@"zip file name" Password:@"password" ];
//壓縮包釋放到的位置,需要一個完整路徑
[zipFile UnzipFileTo:@"output path" overwrite:YES];
[zipFile UnzipCloseFile];
[zipFile release];
//記得釋放
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;
}