使用 glob 获取目录中的文件列表 [英] Getting a list of files in a directory with a glob
问题描述
出于某种疯狂的原因,我找不到一种方法来获取包含给定目录的 glob 的文件列表.
For some crazy reason I can't find a way to get a list of files with a glob for a given directory.
我目前被困在以下方面:
I'm currently stuck with something along the lines of:
NSString *bundleRoot = [[NSBundle mainBundle] bundlePath];
NSArray *dirContents = [[NSFileManager defaultManager]
directoryContentsAtPath:bundleRoot];
..然后去掉我不想要的东西,这很糟糕.但我真正想要的是能够搜索诸如foo*.jpg"之类的内容,而不是请求整个目录,但我找不到类似的内容.
..and then stripping out the stuff I don't want, which sucks. But what I'd really like is to be able to search for something like "foo*.jpg" instead of asking for the entire directory, but I've not been able to find anything like that.
那你是怎么做到的?
推荐答案
在 NSPredicate 的帮助下,您可以很容易地实现这一点,如下所示:
You can achieve this pretty easily with the help of NSPredicate, like so:
NSString *bundleRoot = [[NSBundle mainBundle] bundlePath];
NSFileManager *fm = [NSFileManager defaultManager];
NSArray *dirContents = [fm contentsOfDirectoryAtPath:bundleRoot error:nil];
NSPredicate *fltr = [NSPredicate predicateWithFormat:@"self ENDSWITH '.jpg'"];
NSArray *onlyJPGs = [dirContents filteredArrayUsingPredicate:fltr];
如果你需要用 NSURL 来代替,它看起来像这样:
If you need to do it with NSURL instead it looks like this:
NSURL *bundleRoot = [[NSBundle mainBundle] bundleURL];
NSArray * dirContents =
[fm contentsOfDirectoryAtURL:bundleRoot
includingPropertiesForKeys:@[]
options:NSDirectoryEnumerationSkipsHiddenFiles
error:nil];
NSPredicate * fltr = [NSPredicate predicateWithFormat:@"pathExtension='jpg'"];
NSArray * onlyJPGs = [dirContents filteredArrayUsingPredicate:fltr];
这篇关于使用 glob 获取目录中的文件列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!