iOS返回文件夹下面所有的文件包含子目录

查资料的时候没有找到以返回值的方法,所以自己写了一个.

NSArray *array = [self traversalDirectory:@"www" ofType:@".js"];
/**
 返回文件夹下面所有的文件

 @param path 文件夹
 @param ext 文件类型  eg. @".js"
 @return 所有文件具体路径数组
 */
+ (NSArray *)traversalDirectory:(NSString *) path ofType:(nullable NSString *)ext;{
    NSMutableArray *arrM = [NSMutableArray array];
    NSFileManager * fileManger = [NSFileManager defaultManager];
    BOOL isDir = NO;
    BOOL isExist = [fileManger fileExistsAtPath:path isDirectory:&isDir];
    if (isExist) {
        if (isDir) {
            NSArray * dirArray = [fileManger contentsOfDirectoryAtPath:path error:nil];
            NSString * subPath = nil;
            for (NSString * str in dirArray) {
                subPath  = [path stringByAppendingPathComponent:str];
                BOOL issubDir = NO;
                [fileManger fileExistsAtPath:subPath isDirectory:&issubDir];
                NSArray *tmp = [self showAllFileWithPath:subPath ofType:ext];
                if (tmp.count > 0) {
                    [arrM addObjectsFromArray:tmp];
                }
            }
        }else{
            NSString *fileName = [[path componentsSeparatedByString:@"/"] lastObject];
            if ([fileName hasSuffix:ext]) {
                [arrM addObject:path];
            }
        }
    }else{
        
    }
    return arrM.copy;
}

推荐阅读更多精彩内容