Objective-C 获取目录中的文件和子文件夹列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19925276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 21:09:12  来源:igfitidea点击:

Objective-C get list of files and subfolders in a directory

objective-c

提问by Tsukasa

What is the trick to get an array list of full file/folder paths from a given directory? I'm looking to search a given directory for files ending in .mp3 and need the full path name that includes the filename.

从给定目录获取完整文件/文件夹路径的数组列表的技巧是什么?我希望在给定目录中搜​​索以 .mp3 结尾的文件,并需要包含文件名的完整路径名。

NSArray* dirs = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:sourcePath error:Nil];

NSArray* mp3Files = [dirs filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self ENDSWITH '.mp3'"]];

this only returns the file name not the path

这仅返回文件名而不是路径

回答by trojanfoe

It's probably best to enumerate the array using a block, which can be used to concatenate the path and the filename, testing for whatever file extension you want:

最好使用块枚举数组,该块可用于连接路径和文件名,测试您想要的任何文件扩展名:

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

回答by Infinity James

To use a predicate on URLs I would do it this way:

要在 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];

This question may be a duplicate: Getting a list of files in a directory with a glob

这个问题可能是重复的:Getting a list of files in a directory with a glob

There is also the NSDirectoryEnumeratorobject which is great for iterating through files in a directory.

还有NSDirectoryEnumerator一个非常适合遍历目录中文件的对象。