问题描述
我需要访问文件夹中的每个文件,包括存在于嵌套文件夹中的文件.示例文件夹可能如下所示.
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"中不是文件夹的每个文件运行一个进程.遍历文件夹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:includePropertiesForKeys: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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!