如何检查Cocoa&Objective-C中是否存在文件夹?
如何使用Objective-C检查Cocoa中是否存在文件夹(目录)?
使用NSFileManager
的fileExistsAtPath:isDirectory:
方法。 在这里看到苹果的文档。
Apple在NSFileManager.h中提供了一些关于检查文件系统的好build议:
“尝试一个操作(比如加载一个文件或者创build一个目录)比处理提前搞清楚这个操作是否成功要优雅得多,而且处理这个错误要好得多。试图根据当前状态来判断行为文件系统或文件系统上的特定文件在面对文件系统竞争条件时鼓励奇怪的行为。“
[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.
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! }
如果你有一个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");