目标C - 删除目录中的文件,而不删除zip中的文件

时间:2015-02-13 18:19:10

标签: objective-c macos zip nsfilemanager

如何删除目录中的文件而不删除该目录中zip的相同文件?

以我的文件为例:

它包含log.txt,message.txt,button.txt,log.zip。

在log.zip中,它包含log.txt,message.txt,button.txt。

当我尝试做这样的事情时:

NSArray *zipFiles = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:NSDocumentDirectory error:&error];
for (int i = 0; i < Files.count; i++) {
    id myArrayElement = [Files objectAtIndex:i];
    if ([myArrayElement rangeOfString:@"Button"].location !=NSNotFound || [myArrayElement rangeOfString:@"message"].location !=NSNotFound || [myArrayElement rangeOfString:@"log"].location !=NSNotFound) {
            id myArrayElement = [Files objectAtIndex:i];
            //Clean up the files in that specified directory.
            NSFileManager *fileManager = [NSFileManager defaultManager];
            NSString *filePath = [zipDirectory stringByAppendingPathComponent:myArrayElement];
            BOOL success = [fileManager removeItemAtPath:filePath error:&error];
            if (success) {
                NSLog(@"Successfully cleaned up files in user specified directory.");
            }
            else
            {
                NSLog(@"Could not delete file -:%@ ",[error localizedDescription]);
            }
    }
}

它将删除.zip中的文件以及zip外部的文件,这些文件恰好是同一个名称。我只想删除.zip文件之外的3个文件,而不是.zip文件。

1 个答案:

答案 0 :(得分:0)

您正在测试包含“button”,“msg”或“log”的文件路径。路径“log.txt”和“log.zip”都包含“log”,因此您也删除了您的zip文件。

您没有准确说出要删除的内容,所有非zip文件?所有.txt文件?名称遵循特定模式的文件?文件也包含在同一文件夹中的ZIP中(需要访问代码中的ZIP内容)?

如果它只是.txt文件,您可以测试filePath.extension@"txt",或者如果您希望保持ZIP文件测试不是@"zip"等。如果是名称按照模式考虑NSRegularExpression

HTH

相关问题