您的位置:首页 > 移动开发 > IOS开发

iOS 读取zip包中的文件

2016-09-22 16:31 169 查看
项目需要,最近处理zip包中的文件,经探索有两种方式,分别对应的类库文件为:ZipArchive 和 Objective-Zip。对应的下载地址分别为:

(1)http://ziparchive.googlecode.com/files/ZipArchive.zip
 没法FQ的小伙伴可以去http://download.csdn.net/detail/xiaodragon2008/9621450下载即可
(2)https://github.com/gianlucabertani/Objective-Zip
这两个开源库都具备压缩,和解压缩功能,下面只介绍自己用到的读取Zip包中的功能
1.ZipArchive
这个方法需要首先将压缩包解压到某个目录,然后再从解压到的目录中去读取相应的文件即可,首先引入下载地址中的第三方库文件
下面代码实现的操作是读取本地项目中的20160809.zip包中的文件,解压以后并读取20160809.xml中的文件
NSString *zipPath = [[NSBundle mainBundle] pathForResource:@"20160809" ofType:@"zip"];

NSLog(@" zip path :%@",zipPath);
ZipArchive *za = [[ZipArchive alloc]init];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentpath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
<br>NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *unzipFilePath = [documentpath stringByAppendingPathComponent:@"/test"];

if([za UnzipOpenFile:zipPath])
{
BOOL ret = [za UnzipFileTo:unzipFilePath overWrite:YES];
if(ret == NO){

}
[za UnzipCloseFile];
}

NSString *unzipFullPath = [NSString stringWithFormat:@"%@/20160809.xml",unzipFilePath];
NSData *xmlData = [NSData dataWithContentsOfFile:unzipFullPath options:0 error:nil];
NSDictionary *responseData = [NSDictionary dictionaryWithXMLData:xmlData];

2.Objective-Zip 该方法,可以解压后读取,也可以直接解压到内存中读取,本人为了提高效率,主要采用后面一种处理方式

NSString *zipPath = [[NSBundle mainBundle] pathForResource:@"20160809" ofType:@"zip"];

NSError *error;
OZZipFile *unzipFile = [[OZZipFile alloc]initWithFileName:zipPath mode:OZZipFileModeUnzip error:&error];
if(error != nil)
{
return;
}
NSLog(@"error -- xx %@",error);
//    OZZipFile *unzipFile= [[OZZipFile alloc] initWithFileName:zipPath
//                                                         mode:OZZipFileModeUnzip];

[unzipFile goToFirstFileInZip];
OZFileInZipInfo *info= [unzipFile getCurrentFileInZipInfo];

OZZipReadStream *read= [unzipFile readCurrentFileInZip];
NSMutableData *data= [[NSMutableData alloc] initWithLength:info.length];
[read readDataWithBuffer:data];

// Do something with data
NSData *xmlData = [NSData dataWithData:data];
NSDictionary *responseData = [NSDictionary dictionaryWithXMLData:xmlData];
NSLog(@"responseData %@",responseData);
[read finishedReading];

注意,为了保证有时候读取的文件有可能不是zip文件,所以要做容错处理,要使用

OZZipFile *unzipFile = [[OZZipFile alloc]initWithFileName:zipPath mode:OZZipFileModeUnzip error:&error];
if(error != nil)
{
return;
}<br>而不是如下的初始化zip包文件方法。
OZZipFile *unzipFile= [[OZZipFile alloc] initWithFileName:zipPath mode:OZZipFileModeUnzip];


比如说我曾经遇到过,从服务器中去下载zip包文件,但是出现过下载到本地的zip包文件无法打开,因为服务器给返回的是http请求是200但是没有数据,给我返回一个resultcode,导致程序没法解压该zip包文件,app意外崩溃。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios Zip包解压