2008-09-19 119 views

回答

70

使用NSFileManagerfileExistsAtPath:isDirectory:方法。請參閱Apple的文檔here

+1

沒有確切的。因爲你傳遞一個指向bool的指針作爲`isDirectory`。這意味着如果有一個具有這樣的名字的文件,這個方法返回YES,並將`NO`寫入指針'isDirectory`。 – yas375 2013-09-30 16:06:36

+1

但是,一切都是unix中的文件。 – uchuugaka 2014-01-28 12:09:54

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. 
+0

第一行混淆了`fileExists..`是一個類方法。請更新答案。我本來可以做到的,但它的回答太舊了,如果你會更好。 – 2015-05-09 10:40:38

13

從蘋果在NSFileManager.h關於檢查文件系統的一些很好的建議:

「這是更好的嘗試的操作(如加載文件或創建一個目錄),並優雅地處理錯誤,而不是試圖提前判斷操作是否成功。試圖根據文件系統的當前狀態或文件系統上的特定文件判斷行爲是令人鼓舞的面對文件系統競爭條件的行爲。「

6

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

如果您有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"); 
相關問題