在iPhone上读写zip文件

我查找过很多个iOS的zip文件库,不过我会推荐使用Objective-Zip。它通过一个很自然的Objective-C的接口包装了ZLib和MiniZip,同时提供了很友好的功能来访问归档文件中的元数据。

使用十分简单,从库中提取如下目录并加入到项目中:

ZLib
MiniZip
Objective-Zip

这里是一些如何读写zip文件的示例。

读取zip的内容
// 假设zipFilePath是想要读取的zip文件的路径的字符串   // 打开zip文件

ZipFile *zipFile = [[ZipFile alloc] initWithFileName:zipFilePath mode:ZipFileModeUnzip];
[zipFile goToFirstFileInZip];   
BOOL continueReading = YES;
while (continueReading) {   
    // 获取文件信息
    FileInZipInfo *info = [zipFile getCurrentFileInZipInfo];   
    // 将数据读入缓冲区
    ZipReadStream *stream = [zipFile readCurrentFileInZip];
    NSMutableData *data = [[NSMutableData alloc] initWithLength:info.length];
    [stream readDataWithBuffer:data];   
    // 将数据存入文件
    NSString *writePath = [dataPath stringByAppendingPathComponent:info.name];
    NSError *error = nil;
    [data writeToFile:writePath options:NSDataWritingAtomic error:&error];
    if (error) {
        NSLog(@"Error unzipping file: %@", [error localizedDescription]);
     
    // 清理
    [stream finishedReading];
    [data release];   
    // 检查是否需要继续读取
    continueReading = [zipFile goToNextFileInZip];
  
[zipFile close];

 

提示:Objective-Zip站点上的示例中是初始化一个长度是256的NSMutableData缓冲区… 但我注意到文件会被截断,所以我传入了文件长度。如果要提取内存无法承受的大文件,建议使用网站上介绍的读写缓冲区技术。

将目录内如写入zip文件
// 假设zipFilePath是想要创建的zip文件的路径的字符串
// 假设dataPath是想要压缩的目录   // 创建zip文件

ZipFile *zipFile = [[ZipFile alloc] initWithFileName:zipFilePath mode:ZipFileModeCreate];   
// 读取目录中的文件
NSError *error = nil;
NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:dataPath error:&error];   // 将每个文件写入zip
for (NSString *filename in files) {   
    // 获取文件创建日期
    NSString *path = [dataPath stringByAppendingPathComponent:filename];
    NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:&error];
    NSDate *date = [attributes objectForKey:NSFileCreationDate];  
     // 写文件
    ZipWriteStream *stream = [zipFile writeFileInZipWithName:filename fileDate:date compressionLevel:ZipCompressionLevelBest];
    NSData *data = [NSData dataWithContentsOfFile:path];
    [stream writeData:data];
    [stream finishedWriting];
  
// 关闭zip文件
[zipFile close];

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值