用ZipArchive压缩文件夹

上次有篇博客记录了用ZipArchive压缩文件,但是那段代码有点问题,可以压缩根目录下的文件,但是无法压缩子目录下的文件:

NSArray *fileList = [fileManager contentsOfDirectoryAtPath:sourcePath error:nil];// 文件列表  
for(NSString *fileName in fileList){  
    NSString *filePath = [sourcePath stringByAppendingPathComponent:fileName];// 文件完整路径  
    [zipArchive addFileToZip:filePath newname:fileName];  
}

上面的contentsOfDirectoryAtPath方法,遍历了sourcePath目录,列出所有的文件和子目录。问题是子目录会被压缩成一个无后缀的文件,而不是被当做文件夹来处理。改进了一下,应该用下面的代码:

NSArray *subPaths = [fileManager subpathsAtPath:sourcePath];// 关键是subpathsAtPath方法 
for(NSString *subPath in subPaths){  
    NSString *fullPath = [sourcePath stringByAppendingPathComponent:subPath];  
    BOOL isDir;  
    if([fileManager fileExistsAtPath:fullPath isDirectory:&isDir] && !isDir)// 只处理文件  
    {  
        [zipArchive addFileToZip:fullPath newname:subPath];  
    }  
}

区别在于不是调用contentsOfDirectoryAtPath方法,而是调用subpathsAtPath方法,这会列出sourcePath下的所有文件和子目录,然后在下面的循环里,将文件写入压缩文件,不处理文件夹。注意newname要直接用subPath,这样会自动在压缩文件中保留子目录下的文件完整路径

你可能感兴趣的:(用ZipArchive压缩文件夹)