如何在Cocoa和Objective-C中检查文件夹是否存在?

46

如何使用Objective-C在Cocoa中检查文件夹(目录)是否存在?

5个回答

73

可以使用NSFileManagerfileExistsAtPath:isDirectory:方法。请参阅Apple的文档此处


1
不完全正确。因为你将一个指向布尔值的指针作为 isDirectory 参数传递。这意味着如果有一个同名的文件,该方法会返回 YES 并将 NO 写入指针 isDirectory - yas375

13

苹果公司在NSFileManager.h中针对检查文件系统提出了一些建议:

"尝试执行操作(如加载文件或创建目录)并优雅地处理错误比预先尝试确定操作是否成功要好得多。基于文件系统的当前状态或文件系统上的特定文件来预测行为,会在面对文件系统竞争条件时鼓励产生奇怪的行为。"


文档中也提到了:http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/Reference/Reference.html#//apple_ref/occ/instm/NSFileManager/fileExistsAtPath: - Monolo

10

[NSFileManager fileExistsAtPath:isDirectory:]

Returns a Boolean value that indicates whether a specified file exists.

- (BOOL)fileExistsAtPath:(NSString *)path isDirectory:(BOOL *)isDirectory

Parameters
path
The path of a file or directory. If path begins with a tilde (~), it must first be expanded with stringByExpandingTildeInPath, or this method will return NO.

isDirectory
Upon return, contains YES if path is a directory or if the final path element is a symbolic link that points to a directory, otherwise contains NO. If path doesn’t exist, the return value is undefined. Pass NULL if you do not need this information.

Return Value
YES if there is a file or directory at path, otherwise NO. If path specifies a symbolic link, this method traverses the link and returns YES or NO based on the existence of the file or directory at the link destination.

第一行让人困惑fileExists..是一个类方法。请更新答案。我本可以这样做,但那个答案太旧了,如果您能提供更好的答案就更好了。 - Anoop Vaidya

8

NSFileManager是查找文件相关API的最佳位置。您需要的特定API是- fileExistsAtPath:isDirectory:

示例:

NSString *pathToFile = @"...";
BOOL isDir = NO;
BOOL isFile = [[NSFileManager defaultManager] fileExistsAtPath:pathToFile isDirectory:&isDir];

if(isFile)
{
    //it is a file, process it here how ever you like, check isDir to see if its a directory 
}
else
{
    //not a file, this is an error, handle it!
}

1
这个解决方案不起作用。 - Ketan P

2

如果您有一个NSURL对象作为path,最好使用path将其转换为NSString

NSFileManager*fm = [NSFileManager defaultManager];

NSURL* path = [[[fm URLsForDirectory:NSDocumentDirectory 
                           inDomains:NSUserDomainMask] objectAtIndex:0]                           
                                 URLByAppendingPathComponent:@"photos"];

NSError *theError = nil;
if(![fm fileExistsAtPath:[path path]]){
    NSLog(@"dir doesn't exists");
}else
    NSLog(@"dir exists");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接