File search with specific Extension Objective c

后端 未结 6 1484
我在风中等你
我在风中等你 2020-12-11 07:36

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

相关标签:
6条回答
  • 2020-12-11 08:16

    Yes we have direct method for NSArray below helps you

     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"
    
    0 讨论(0)
  • 2020-12-11 08:19

    see using NSFileManager you can get the files and bellow the condition with you can get file with particular extension, Its work in Document Directory ..

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

    use this array with your searched files.. get the return in NSArray type so use NSArray object to store this data...

    i hope this helpful to you...

    0 讨论(0)
  • 2020-12-11 08:26

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

    Now the recursive Method

    -(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;
    }
    
    0 讨论(0)
  • 2020-12-11 08:26

    Like this way you can find your specific file extension

     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]];
    
    
            }
    
        }
    
    0 讨论(0)
  • 2020-12-11 08:31

    Use below code

    NSArray *myFiles = [myBundle pathsForResourcesOfType:@"Your File extension"
                                        inDirectory:nil];
    
    0 讨论(0)
  • 2020-12-11 08:32

    What you need is a recursive method so that you can process sub-directories. The first of the following methods is public; the other private. Imagine they are implemented as static methods of a class called 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
    

    This will return an array containing the full path to every file with the specified file extension. Note that [NSString pathExtension] does not return the . of the file extension so be sure not to pass that in the extension parameter.

    0 讨论(0)
提交回复
热议问题