我正在尝试删除文档目录中扩展名为“.jpg”的所有文件,经过多次尝试后,我仍然无法成功。
我现在的代码是:
-(void)removeOneImage:(NSString*)fileName {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.jpg", fileName]];
[fileManager removeItemAtPath: fullPath error:NULL];
}
使用此代码我可以删除一个具有特定名称的文件。
有人可以帮我删除具有特定扩展名的所有文件吗?
亲切的问候,
多雪
答案 0 :(得分:37)
NSString *extension = @"jpg";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *contents = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:NULL];
NSEnumerator *e = [contents objectEnumerator];
NSString *filename;
while ((filename = [e nextObject])) {
if ([[filename pathExtension] isEqualToString:extension]) {
[fileManager removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:filename] error:NULL];
}
}
答案 1 :(得分:3)
// Get the Documents directory path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
// Delete the file using NSFileManager
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager removeItemAtPath:[documentsDirectoryPath stringByAppendingPathComponent:yourFile.txt] error:nil];
了解更多信息
How to delete ALL FILES in a specified directory on the app?
答案 2 :(得分:2)
非常简单的方法:
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *imageName = [NSString stringWithFormat:@"demo.jpg"];
[fileManager removeItemAtPath:imageName error:NULL];
答案 3 :(得分:1)
如果您更喜欢快速枚举:
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *extension = @"jpg";
NSArray *contents = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:nil];
for (NSString *file in contents) {
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:file];
if ( ([[file pathExtension] isEqualToString:extension]) && [fileManager isDeletableFileAtPath:filePath] ) {
[fileManager removeItemAtPath:filePath error:nil];
}
}