objective-c - 苹果操作系统 : how to determine path is file or directory

标签 objective-c macos file filesystems nsfilemanager

我有一个路径,我想知道,是这个目录还是一个文件。很简单,但我有一个问题。这是我的路径:

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/

相关文章:

objective-c - block 内函数的返回值

objective-c - Swift 中 NSCoding 协议(protocol)的实现有什么问题

cocoa - 如何在运行时在 NSButton 上独立缩放轴

swift - 使用 IOKit 和 Swift 进行简单的键重映射

java - 在 Android Studio 中加载文件

file - Maven package 在 jar 包中打开一个文件(作为 *File*)

ios - 如何在IOS中用横向图像填充背景?

ios - 设置新文本后,NSTextView 将停止滚动

c++ - 从 C 代码调用具有复杂参数和复杂返回类型的 C++ 函数

c - 使用C同步文件夹