我有一个路径,我想知道,是这个目录还是一个文件。很简单,但我有一个问题。这是我的路径:
NSString *file = @"file://localhost/Users/myUser/myFolder/TestFolder/";
或
NSString *file = @"file://localhost/Users/myUser/myFolder/my_test_file.png";
这是我的代码:
BOOL isDir;
// the original code from apple documentation:
// if ([fileManager fileExistsAtPath:file isDirectory:&isDir] && isDir)
// but even my if returns me "not ok" in log
if([[NSFileManager defaultManager] fileExistsAtPath:file isDirectory:&isDir])
{
NSLog(@"directory");
}
else
{
NSLog(@"not ok");
}
此路径上的文件和目录都存在并且没问题。但我认为问题可能出在里面。但我不知道为什么。请帮我解决这个问题。
顺便说一句,我从另一种方法获取路径:
NSArray *contentOfMyFolder = [[NSFileManager defaultManager]
contentsOfDirectoryAtURL:urlFromBookmark
includingPropertiesForKeys:@[NSURLContentModificationDateKey, NSURLLocalizedNameKey]
options:NSDirectoryEnumerationSkipsHiddenFiles
error:nil];
在 for 循环之后,我得到存储在数组 contentOfMyFolder
中的项目
并获得这样的路径:
for (id item in contentOfMyFolder) {
NSString *path = [item absoluteString];
}
我认为这是方法 fileExistsAtPath:(NSString *)path isDirectory:(BOOL)isDir
的完全有效路径
问题可能隐藏在哪里?!
最佳答案
问题出在这里:
NSString *path = [item absoluteString];
因为这会创建 URL 的字符串表示形式,例如
file://localhost/Users/myUser/myFolder/TestFolder/
这不是 fileExistsAtPath:
所期望的。
您需要的是将 URL 转换为路径的 path
方法:
for (NSURL *item in contentOfMyFolder) {
NSString *path = [item path];
BOOL isDir;
if ([[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDir]) {
if (isDir) {
NSLog(@"%@ is a directory", path);
} else {
NSLog(@"%@ is a file", path);
}
} else {
NSLog(@"Oops, %@ does not exist?", path);
}
}
或者,您可以向 URL 询问其“目录属性”:
for (NSURL *item in contentOfMyFolder) {
NSNumber *isDir;
NSError *error;
if ([item getResourceValue:&isDir forKey:NSURLIsDirectoryKey error:&error]) {
if ([isDir boolValue]) {
NSLog(@"%@ is a directory", item);
} else {
NSLog(@"%@ is a file", item);
}
} else {
NSLog(@"error: %@", error);
}
}
关于objective-c - 苹果操作系统 : how to determine path is file or directory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18513781/