我有以下代码,它返回给定目录中文件名的NSArray
。当目录存在时,这可以正常工作,但我想知道的是我如何首先检查 directoryPath 中的目录是否确实存在。
NSString *directoryPath = [documentsDirectory stringByAppendingPathComponent:folderName];
NSArray *directoryContents = [[NSFileManager defaultManager]contentsOfDirectoryAtPath:directoryPath error:nil];
答案 0 :(得分:1)
使用NSFileManager的fileExistsAtPath:isDirectory:method。
答案 1 :(得分:1)
fileExistsAtPath:isDirectory:
返回值 如果指定路径中的文件存在,则为YES;如果文件不存在或无法确定其存在,则为NO。
答案 2 :(得分:1)
以下NSFileManger API可以提供所需的结果:
答案 3 :(得分:1)
使用此:
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *pathToDocumentsDir = [paths objectAtIndex:0];
BOOL isDir;
NSString *subfolder = [pathToDocumentsDir stringByAppendingPathComponent:fileExistsAtPath:YOUR_DIRECTORY_NAME];
if (![fileManager fileExistsAtPath:subfolder isDirectory:&isDir]) {
//No directory exist
[fileManager createDirectoryAtPath:subfolder withIntermediateDirectories:NO attributes:nil error:nil];
}
else{
//directory exist
}
答案 4 :(得分:1)
示例代码:
NSString *directoryPath = [documentsDirectory stringByAppendingPathComponent:folderName];
BOOL isDirectory;
BOOL isExists = [[NSFileManager defaultManager] fileExistsAtPath:directoryPath isDirectory:&isDirectory];
if (isExists) {
/* file exists */
if (isDirectory) {
/* file is a directory */
}
}
答案 5 :(得分:1)
NSFileManager
类有一个内置方法,用于检查路径中是否存在文件。
功能如下:
[fileManagerObject fileExistsAtPath : @"PUT_YOUR_FILE_PATH_HERE" isDirectory : YES]; //If its a file that you're looking to check then put isDirectory as NO, but if its a folder then enter YES as the parameter
以下是您在代码中通常使用它的方法:
NSFileManager *fileManager = [[NSFileManager alloc] init];
if([fileManager fileExistsAtPath:@"FILE_PATH_HERE" isDirectory:NO] == YES)
{
//Yes. The file exists, continue with your operation.
}
else
{
//No. The file doesn't exist.
}