在iPhone上读写zip文件

来源:互联网 发布:网站怎么导入数据库 编辑:程序博客网 时间:2024/06/11 22:01

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

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

ZLibMiniZipObjective-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];


原创粉丝点击