min*_*pop 41 directory iteration macos cocoa
我需要访问文件夹中的每个文件,包括嵌套文件夹中存在的文件.示例文件夹可能如下所示.
animals/
-k.txt
-d.jpg
cat/
-r.txt
-z.jpg
tiger/
-a.jpg
-p.pdf
dog/
-n.txt
-f.jpg
-p.pdf
Run Code Online (Sandbox Code Playgroud)
假设我想在不是文件夹的"动物"中的每个文件上运行一个进程.迭代文件夹"animals"及其所有子文件夹访问每个文件的最佳方法是什么?
谢谢.
小智 95
使用NSDirectoryEnumerator
递归枚举你想要的目录下的文件和目录,并要求它要告诉你它是否是一个文件或目录.以下内容基于以下文档中列出的示例-[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
}
}
Run Code Online (Sandbox Code Playgroud)
Kar*_*oor 25
也许你可以使用这样的东西:
+(void)openEachFileAt:(NSString*)path
{
NSDirectoryEnumerator* enumerator = [[NSFileManager defaultManager] enumeratorAtPath:path];
for (NSString * file in enumerator)
{
// check if it's a directory
BOOL isDirectory = NO;
NSString* fullPath = [path stringByAppendingPathComponent:file];
[[NSFileManager defaultManager] fileExistsAtPath:fullPath
isDirectory: &isDirectory];
if (!isDirectory)
{
// open your file (fullPath)…
}
else
{
[self openEachFileAt: fullPath];
}
}
}
Run Code Online (Sandbox Code Playgroud)
Esq*_*uth 14
这是一个快速版本:
func openEachFile(inDirectory path: String) {
let subs = try! FileManager.default.subpathsOfDirectory(atPath: path)
let totalFiles = subs.count
print(totalFiles)
for sub in subs {
if sub.hasPrefix(".DS_Store") {
//a DS_Store file
}
else if sub.hasSuffix(".xcassets") {
//a xcassets file
}
else if (sub as NSString).substring(to: 4) == ".git" {
//a git file
}
else if sub.hasSuffix(".swift") {
//a swift file
}
else if sub.hasSuffix(".m") {
//a objc file
}
else if sub.hasSuffix(".h") {
//a header file
}
else {
// some other file
}
let fullPath = (path as NSString).appendingPathComponent(sub)
}
}
Run Code Online (Sandbox Code Playgroud)