迭代文件夹中的文件夹与嵌套文件夹 - Cocoa [英] Iterating through files in a folder with nested folders - Cocoa

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

问题描述

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

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

说,我想对animals中不是文件夹的每个文件运行一个进程。



感谢。

div class =h2_lin>解决方案

使用 NSDirectoryEnumerator 递归枚举所需目录下的文件和目录,它是一个文件或目录。下面是基于 - [NSFileManager enumeratorAtURL:includePropertiesForKeys:options:errorHandler:] 的文档中列出的示例:

  NSFileManager * fileManager = [NSFileManager defaultManager]; 
NSURL * directoryURL = ... //指向要浏览的目录的URL
NSArray * keys = [NSArray arrayWithObject:NSURLIsDirectoryKey];

NSDirectoryEnumerator * enumerator = [fileManager
enumeratorAtURL:directoryURL
includePropertiesForKeys:keys
options:0
errorHandler:^(NSURL * url,NSError * error ){
//处理错误。
//如果在错误后继续枚举,则返回YES。
return YES;
}];

for(NSURL * url in enumerator){
NSError * error;
NSNumber * isDirectory = nil;
if(![url getResourceValue:& isDirectory forKey:NSURLIsDirectoryKey错误:&错误]){
//句柄错误
}
else if(![isDirectory boolValue] ){
//没有错误,它不是一个目录;使用文件
}
}


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

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?

Thanks.

解决方案

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:^(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天全站免登陆