遍历具有嵌套文件夹的文件夹中的文件 - Cocoa [英] Iterating through files in a folder with nested folders - Cocoa

查看:41
本文介绍了遍历具有嵌套文件夹的文件夹中的文件 - Cocoa的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要访问文件夹中的每个文件,包括嵌套文件夹中存在的文件.示例文件夹可能如下所示.

I need to access every file in a folder, including file that exist within nested folders. An example folder might look like this.

animals/
 -k.txt
 -d.jpg
 cat/
   -r.txt
   -z.jpg
   tiger/
      -a.jpg
      -p.pdf
 dog/
   -n.txt
   -f.jpg
 -p.pdf

假设我想对动物"中不是文件夹的每个文件运行一个进程.遍历文件夹animals"及其所有子文件夹以访问每个文件的最佳方法是什么?

Say that I wanted to run a process on every file within "animals" that isn't folder. What would be the best way to iterate through the folder "animals" and all of its subfolders to access every file?

谢谢.

推荐答案

使用NSDirectoryEnumerator递归枚举你想要的目录下的文件和目录,并要求它告诉你是文件还是目录.以下基于 -[NSFileManager enumeratorAtURL:includingPropertiesForKeys:options:errorHandler:]:

Use NSDirectoryEnumerator to recursively enumerate files and directories under the directory you want, and ask it to tell you whether it is a file or directory. The following is based on the example listed at the documentation for -[NSFileManager enumeratorAtURL:includingPropertiesForKeys:options:errorHandler:]:

NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *directoryURL = … // URL pointing to the directory you want to browse
NSArray *keys = [NSArray arrayWithObject:NSURLIsDirectoryKey];

NSDirectoryEnumerator *enumerator = [fileManager
    enumeratorAtURL:directoryURL
    includingPropertiesForKeys:keys
    options:0
    errorHandler:^BOOL(NSURL *url, NSError *error) {
        // Handle the error.
        // Return YES if the enumeration should continue after the error.
        return YES;
}];

for (NSURL *url in enumerator) { 
    NSError *error;
    NSNumber *isDirectory = nil;
    if (! [url getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:&error]) {
        // handle error
    }
    else if (! [isDirectory boolValue]) {
        // No error and it’s not a directory; do something with the file
    }
}

这篇关于遍历具有嵌套文件夹的文件夹中的文件 - Cocoa的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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