为了账号安全,请及时绑定邮箱和手机立即绑定

使用glob获取目录中的文件列表

使用glob获取目录中的文件列表

iOS
尚方宝剑之说 2019-10-05 13:19:27
出于某种疯狂的原因,我无法找到一种方法来获取给定目录的文件列表。我目前在以下方面陷入困境:NSString *bundleRoot = [[NSBundle mainBundle] bundlePath];NSArray *dirContents = [[NSFileManager defaultManager]                         directoryContentsAtPath:bundleRoot];..然后去掉我不想要的东西,这很烂。但是我真正想要的是能够搜索“ foo * .jpg”之类的内容,而不是查询整个目录,但是我却找不到类似的东西。那你怎么做到的呢?
查看完整描述

3 回答

?
小唯快跑啊

TA贡献1863条经验 获得超2个赞

您可以借助NSPredicate轻松实现此目标,如下所示:


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代替,它看起来像这样:


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


查看完整回答
反对 回复 2019-10-05
?
慕工程0101907

TA贡献1887条经验 获得超5个赞

这非常适合IOS,但也应该适用cocoa。


NSString *bundleRoot = [[NSBundle mainBundle] bundlePath];

NSFileManager *manager = [NSFileManager defaultManager];

NSDirectoryEnumerator *direnum = [manager enumeratorAtPath:bundleRoot];

NSString *filename;


while ((filename = [direnum nextObject] )) {


    //change the suffix to what you are looking for

    if ([filename hasSuffix:@".data"]) {   


        // Do work here

        NSLog(@"Files in resource folder: %@", filename);            

    }       

}


查看完整回答
反对 回复 2019-10-05
?
慕侠2389804

TA贡献1719条经验 获得超6个赞

如何使用NSString的hasSuffix和hasPrefix方法?类似于(如果您要搜索“ foo * .jpg”):


NSString *bundleRoot = [[NSBundle mainBundle] bundlePath];

NSArray *dirContents = [[NSFileManager defaultManager] directoryContentsAtPath:bundleRoot];

for (NSString *tString in dirContents) {

    if ([tString hasPrefix:@"foo"] && [tString hasSuffix:@".jpg"]) {


        // do stuff


    }

}

对于像这样的简单,直接的匹配,它比使用正则表达式库更简单。


查看完整回答
反对 回复 2019-10-05
  • 3 回答
  • 0 关注
  • 722 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信