【问题标题】:how to get all files in a directory in ipad using objective c如何使用objective c获取ipad目录中的所有文件
【发布时间】:2012-03-29 00:19:48
【问题描述】:

我需要获取一个目录中的所有文件,包括所有子目录和每个子目录中的所有文件。在目标 C 中,我尝试使用这种方法 [[NSFileManager defaultManager] contentsOfDirectoryAtPath:filePath error:nil]

但它只是给我一个目录filePath中的内容文件数组,我无法获取子目录中的所有文件,有人可以帮助我吗??

谢谢

【问题讨论】:

    标签: objective-c ipad ios5 nsfilemanager


    【解决方案1】:
    - (void)scanPath:(NSString *) sPath {
    
        BOOL isDir;
    
        [[NSFileManager defaultManager] fileExistsAtPath:sPath isDirectory:&isDir];
    
        if(isDir)
        {
            NSArray *contentOfDirectory=[[NSFileManager defaultManager] contentsOfDirectoryAtPath:sPath error:NULL];
    
            int contentcount = [contentOfDirectory count];
            int i;
            for(i=0;i<contentcount;i++)
            {
                NSString *fileName = [contentOfDirectory objectAtIndex:i];
                NSString *path = [sPath stringByAppendingFormat:@"%@%@",@"/",fileName];
    
    
                if([[NSFileManager defaultManager] isDeletableFileAtPath:path])
                {   
                    NSLog(path);
                    [self scanPath:path];
                }
            }
    
        }
        else
        {
            NSString *msg=[NSString stringWithFormat:@"%@",sPath];
            NSLog(msg);
        }
    }
    

    你可以调用这个函数来记录目录中的所有文件,希望这会有所帮助。

    【讨论】:

    • @Risma 这是我在聊天室中提到的递归解决方案的类型。
    • @Risma 请确保感谢正确的人:)
    • @rajesh.adhi,我要感谢你们俩,Chris L 和 arun.s 也感谢你们 rajesh :)
    • 如何避免隐藏文件??
    【解决方案2】:

    您想使用 enumeratorAtURL:includingPropertiesForKeys:options:error: 代替。默认情况下会进行深度枚举:

    NSURL *myDirectoryURL = [[NSBundle mainBundle] URLForResource:@"Assets" withExtension:@""];
    NSDirectoryEnumerator *directoryEnumerator = [[NSFileManager defaultManager] enumeratorAtURL:myDirectoryURL includingPropertiesForKeys:[NSArray array] options:0 errorHandler:^BOOL(NSURL *url, NSError *error) {
        // handle error
        return NO;
    }];
    
    NSString *fileOrDirectory = nil;
    while ((fileOrDirectory = [directoryEnumerator nextObject])) {
        // use file or directory
    }
    

    options 参数可让您指定深或浅枚举。

    https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/Reference/Reference.html

    【讨论】:

    • 能把每个目录下的所有文件都给我吗?
    • 抱歉 -- 应该是 enumeratorAtURL -- 这行得通,经过测试
    • 这是一条看起来很糟糕的作业线。
    • @RichardJ.RossIII 谢谢,我试试 :)。我不确定为什么苹果将错误处理放在一个块中——我想你可以在上面创建错误处理块并将其传递进去。
    猜你喜欢
    • 2022-07-05
    • 2016-03-07
    • 2014-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-15
    • 1970-01-01
    相关资源
    最近更新 更多