如何使用Objective-C在Cocoa中检查文件夹(目录)是否存在?
苹果公司在NSFileManager.h中针对检查文件系统提出了一些建议:
"尝试执行操作(如加载文件或创建目录)并优雅地处理错误比预先尝试确定操作是否成功要好得多。基于文件系统的当前状态或文件系统上的特定文件来预测行为,会在面对文件系统竞争条件时鼓励产生奇怪的行为。"
[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 VaidyaNSFileManager是查找文件相关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!
}
如果您有一个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");
isDirectory
参数传递。这意味着如果有一个同名的文件,该方法会返回 YES 并将NO
写入指针isDirectory
。 - yas375