【问题标题】:File search with specific Extension Objective c具有特定扩展目标 c 的文件搜索
【发布时间】:2012-12-16 02:50:49
【问题描述】:

我正在处理 iPhone 项目中的一些文件操作。我需要在哪里搜索特定扩展名的文件。一种选择是手动处理要查找的每个文件和目录。 我的问题是,有什么简单的方法吗?

谢谢

【问题讨论】:

  • 在哪里搜索这些文件,因为应用沙盒会阻止您在大多数地方查找?
  • 我想搜索 NSDocumentDirectory 中的文件。
  • @AmjadKhan 使用NSFileManager 类。可以返回指定目录下的所有文件名。
  • @H2CO3 他可能也想让方法递归......
  • @trojanfoe NSFileManager 会阻止方法递归吗?我不这么认为......

标签: iphone objective-c ios ipad cocoa


【解决方案1】:

您需要的是一种递归方法,以便您可以处理子目录。以下方法中的第一个是公共的;另一个私人。想象一下,它们被实现为一个名为 CocoaUtil 的类的静态方法:

CocoaUtil.h:

@interface CocoaUtil : NSObject

+ (NSArray *)findFilesWithExtension:(NSString *)extension
                           inFolder:(NSString *)folder;

@end

CocoaUtil.m:

// Private Methods
@interface CocoaUtil ()

+ (NSArray *)_findFilesWithExtension:(NSString *)extension
                            inFolder:(NSString *)folder
                        andSubFolder:(NSString *)subFolder;

@end

@implementation CocoaUtil

+ (NSArray *)findFilesWithExtension:(NSString *)extension
                           inFolder:(NSString *)folder
{
    return [CocoaUtil _findFilesWithExtension:extension
                                     inFolder:folder
                                 andSubFolder:nil];
}

+ (NSArray *)_findFilesWithExtension:(NSString *)extension
                            inFolder:(NSString *)folder
                        andSubFolder:(NSString *)subFolder
{
    NSMutableArray *found = [NSMutableArray array];
    NSString *fullPath = (subFolder != nil) ? [folder stringByAppendingPathComponent:subFolder] : folder;

    NSFileManager *fileman = [NSFileManager defaultManager];
    NSError *error;
    NSArray *contents = [fileman contentsOfDirectoryAtPath:fullPath error:&error];
    if (contents == nil)
    {
        NSLog(@"Failed to find files in folder '%@': %@", fullPath, [error localizedDescription]);
        return nil;
    }

    for (NSString *file in contents)
    {
        NSString *subSubFolder = subFolder != nil ? [subFolder stringByAppendingPathComponent:file] : file;
        fullPath = [folder stringByAppendingPathComponent:subSubFolder];

        NSError *error = nil;
        NSDictionary *attributes = [fileman attributesOfItemAtPath:fullPath error:&error];
        if (attributes == nil)
        {
            NSLog(@"Failed to get attributes of file '%@': %@", fullPath, [error localizedDescription]);
            continue;
        }

        NSString *type = [attributes objectForKey:NSFileType];

        if (type == NSFileTypeDirectory)
        {
            NSArray *subContents = [CocoaUtil _findFilesWithExtension:extension inFolder:folder andSubFolder:subSubFolder];
            if (subContents == nil)
                return nil;
            [found addObjectsFromArray:subContents];
        }
        else if (type == NSFileTypeRegular)
        {
            // Note: case sensitive comparison!
            if ([[fullPath pathExtension] isEqualToString:extension])
            {
                [found addObject:fullPath];
            }
        }
    }

    return found;
}

@end

这将返回一个数组,其中包含具有指定文件扩展名的每个文件的完整路径。请注意,[NSString pathExtension] 不会返回文件扩展名的 .,因此请确保不要在 extension 参数中传递它。

【讨论】:

  • 将 NSArray *subContents = ...... 替换为 NSArray *subContents = [CocoaUtil _findFilesWithExtension:extension inFolder:folder andSubFolder:subSubFolder];它工作正常。谢谢!
【解决方案2】:

使用下面的代码

NSArray *myFiles = [myBundle pathsForResourcesOfType:@"Your File extension"
                                    inDirectory:nil];

【讨论】:

    【解决方案3】:

    我还没有发现任何我可以说很简单的事情,最后我必须编写自己的代码才能做到这一点。我在此处发布此内容是因为也许有人觉得此帮助已满。

    -(void)search{
    @autoreleasepool {
        NSString *baseDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
        NSFileManager *defFM = [NSFileManager defaultManager];
        BOOL isDir = YES;
    
            NSArray *fileTypes = [[NSArray alloc] initWithObjects:@"mp3",@"mp4",@"avi",nil];
            NSMutableArray *mediaFiles = [self searchfiles:baseDir ofTypes:fileTypes];
            NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
            NSString *filePath = [docDir stringByAppendingPathComponent:@"playlist.plist"];
            if(![defFM fileExistsAtPath:filePath isDirectory:&isDir]){
                [defFM createFileAtPath:filePath contents:nil attributes:nil];
            }
    
            NSMutableDictionary *playlistDict = [[NSMutableDictionary alloc]init];
            for(NSString *path in mediaFiles){
                NSLog(@"%@",path);
                [playlistDict setValue:[NSNumber numberWithBool:YES] forKey:path];
            }
    
            [playlistDict writeToFile:filePath atomically:YES];
    
            [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshplaylist" object:nil];
        }
    
    }
    

    现在是递归方法

    -(NSMutableArray*)searchfiles:(NSString*)basePath ofTypes:(NSArray*)fileTypes{
        NSMutableArray *files = [[[NSMutableArray alloc]init] autorelease];
        NSFileManager *defFM = [NSFileManager defaultManager];
        NSError *error = nil;
        NSArray *dirPath = [defFM contentsOfDirectoryAtPath:basePath error:&error];
        for(NSString *path in dirPath){
           BOOL isDir;
           path = [basePath stringByAppendingPathComponent:path];
           if([defFM fileExistsAtPath:path isDirectory:&isDir] && isDir){
              [files addObjectsFromArray:[self searchfiles:path ofType:fileTypes]];
           }
        }
    
    
       NSArray *mediaFiles = [dirPath pathsMatchingExtensions:fileTypes];
       for(NSString *fileName in mediaFiles){
          fileName = [basePath stringByAppendingPathComponent:fileName];
          [files addObject:fileName];
       }
    
       return files;
    }
    

    【讨论】:

      【解决方案4】:

      这样你可以找到你的特定文件扩展名

       NSString *bundleRoot = [[NSBundle mainBundle] bundlePath];
          NSFileManager *manager = [NSFileManager defaultManager];
          NSDirectoryEnumerator *direnum = [manager enumeratorAtPath:bundleRoot];
      
          NSString *filename;
      
          while ((filename = [direnum nextObject] )) {
      
      
              if ([filename hasSuffix:@".doc"]) {   //change the suffix to what you are looking for
      
      
                  [arrayListofFileName addObject:[filename stringByDeletingPathExtension]];
      
      
              }
      
          }
      

      【讨论】:

        【解决方案5】:

        是的,我们有下面的 NSArray 直接方法可以帮助您

         NSMutableArray *arrayFiles = [[NSMutableArray alloc] initWithObjects:@"a.png", @"a.jpg",  @"a.pdf", @"h.png", @"f.png", nil];
            NSLog(@"pathsMatchingExtensions----%@",[arrayFiles pathsMatchingExtensions:[NSArray arrayWithObjects:@"png", nil]]);
        
        //my output is
        "a.png",
        "h.png",
        "f.png"
        

        【讨论】:

          【解决方案6】:

          请参阅使用NSFileManager,您可以获得文件并在以下条件下您可以获得具有特定扩展名的文件,它在文档目录中工作..

          -(NSArray *)findFiles:(NSString *)extension
          {
              NSMutableArray *matches = [[NSMutableArray alloc]init];
              NSFileManager *manager = [NSFileManager defaultManager];
          
              NSString *item;
              NSArray *contents = [manager contentsOfDirectoryAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] error:nil];
              for (item in contents)
              {
                  if ([[item pathExtension]isEqualToString:extension])
                  {
                      [matches addObject:item];
                  }
              }
          
              return matches;
          }
          

          将此数组与您搜索的文件一起使用。在NSArray 类型中获取返回,因此使用NSArray 对象来存储此数据...

          希望对你有帮助...

          【讨论】:

          • @AmjadKhan 也看到这个链接stackoverflow.com/questions/11646325/…
          • 感谢您的回复,但我知道这一点,而且我的问题是我有多个目录和子目录。如果我这样做,可能需要一点时间来处理所有文件。我正在寻找更快的东西。
          • @AmjadKhan 看到这个链接stackoverflow.com/questions/1567134/… 你也可以更改字典名称,是的,还可以根据你的要求设置路径,试试吧..
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-12-21
          • 1970-01-01
          • 2021-05-29
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多