使用特定扩展目标的文件搜索c [英] File search with specific Extension Objective c

查看:102
本文介绍了使用特定扩展目标的文件搜索c的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am working on some file manipulation in iPhone project. Where i need to search files of specific extension. One option is to manually process each file & directory to find. My Question is, Is there any simple way to do that ?

谢谢

推荐答案

我没有发现任何我可以说是简单的事情,最后我要写我自己的代码来做到这一点。我在这里发布,因为也许有人找到这个帮助充分。

I have not found any thing which i could say is simple to do that & and finally i have to write my own code to do this. I am posting this here because maybe someone find this help full.

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

这篇关于使用特定扩展目标的文件搜索c的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆