Objective-C获取目录中的文件和子文件夹列表
从给定目录获取完整文件/文件夹路径的数组列表的技巧是什么? 我想在给定的目录中搜索以.mp3结尾的文件,并需要包含文件名的完整路径名Objective-C获取目录中的文件和子文件夹列表,objective-c,Objective C,从给定目录获取完整文件/文件夹路径的数组列表的技巧是什么? 我想在给定的目录中搜索以.mp3结尾的文件,并需要包含文件名的完整路径名 NSArray* dirs = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:sourcePath error:Nil]; NSArray* mp3Files = [dirs filteredArrayUsingPredicate:[NSPredicate predicateWithForma
NSArray* dirs = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:sourcePath error:Nil];
NSArray* mp3Files = [dirs filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self ENDSWITH '.mp3'"]];
这只返回文件名而不是路径要在URL上使用谓词,我会这样做:
NSURL *bundleRoot = [[NSBundle mainBundle] bundleURL];
NSArray * dirContents =
[fm contentsOfDirectoryAtURL:bundleRoot
includingPropertiesForKeys:@[]
options:NSDirectoryEnumerationSkipsHiddenFiles
error:nil];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"pathExtension='.mp3'"];
NSArray *mp3Files = [directoryContents filteredArrayUsingPredicate:predicate];
这个问题可能是重复的:
还有一个
NSDirectoryEnumerator
对象,它非常适合遍历目录中的文件。最好使用块枚举数组,该块可用于连接路径和文件名,测试您想要的任何文件扩展名:
NSArray* dirs = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:sourcePath
error:NULL];
NSMutableArray *mp3Files = [[NSMutableArray alloc] init];
[dirs enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSString *filename = (NSString *)obj;
NSString *extension = [[filename pathExtension] lowercaseString];
if ([extension isEqualToString:@"mp3"]) {
[mp3Files addObject:[sourcePath stringByAppendingPathComponent:filename]];
}
}];
如何填充
dirs
文件?此处的MP3文件也仅包含文件名,而不包含文件的完整路径。