45

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

4

5 回答 5

73

使用NSFileManager'sfileExistsAtPath:isDirectory:方法。在此处查看 Apple 的文档。

于 2008-09-19T03:52:50.310 回答
13

Apple 在 NSFileManager.h 中提供了一些关于检查文件系统的好建议:

“尝试操作(例如加载文件或创建目录)并优雅地处理错误比尝试提前确定操作是否成功要好得多。尝试根据当前状态来判断行为面对文件系统竞争条件,文件系统或文件系统上的特定文件正在鼓励奇怪的行为。”

于 2010-09-23T08:58:39.170 回答
10

[NSFileManager 文件ExistsAtPath: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.
于 2008-09-19T03:56:23.483 回答
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!
}
于 2012-04-21T12:10:21.783 回答
2

如果您有一个NSURL对象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");
于 2013-04-11T19:09:01.833 回答