本文整理在 iOS 開發中,圍繞 NSFileManager 的檔案與目錄操作、路徑處理工具,以及幾個常用的沙盒目錄。
-(NSData *)contentsAtPath:path //從檔案讀取資料
-(BOOL)createFileAtPath:path contents:(NSData *)data attributes:attr //向檔案寫入資料
-(BOOL)removeItemAtPath:path error:err //刪除檔案
-(BOOL)moveItemAtPath:from toPath:to error:err //重新命名或移動檔案(to 不可為已存在路徑)
-(BOOL)copyItemAtPath:from toPath:to error:err //複製檔案(to 不可為已存在路徑)
-(BOOL)contentsEqualAtPath:path andPath:path2 //比較兩個檔案的內容
-(BOOL)fileExistAtPath:path //判斷檔案是否存在
-(BOOL)isReadableFileAtPath:path //判斷檔案是否存在且可讀
-(BOOL)isWriteableFileAtPath:path //判斷檔案是否存在且可寫
-(NSDictionary *)attributesOfItemAtPath:path error:err //取得檔案屬性
-(BOOL)setAttributesOfItemAtPath:attr error:err //修改檔案屬性
-(NSString *)currentDirectoryPath //取得目前目錄
-(BOOL)changeCurrentDirectoryPath:path //變更目前目錄
-(BOOL)copyItemAtPath:from toPath:to error:err //複製目錄結構(to 不可為已存在路徑)
-(BOOL)createDirectoryAtPath:path withIntermediateDirectories:(BOOL)flag attribute:attr //建立新目錄
-(BOOL)fileExistAtPath:path isDirectory:(BOOL*)flag //判斷是否為目錄(flag 回傳 YES/NO)
-(NSArray *)contentsOfDirectoryAtPath:path error:err //列出目錄內容
-(NSDirectoryEnumerator *)enumeratorAtPath:path //列舉目錄內容
-(BOOL)removeItemAtPath:path error:err //刪除空目錄
-(BOOL)moveItemAtPath:from toPath:to error:err //重新命名或移動目錄(to 不可為已存在路徑)
+(NSString *)pathWithComponents:components //依 components 元素組出有效路徑
-(NSArray *)pathComponents //拆解路徑,取得各組成部分
-(NSString *)lastPathComponent //取出路徑的最後一段
-(NSString *)pathExtension //取出副檔名
-(NSString *)stringByAppendingPathComponent:path //在路徑後面附加子路徑
-(NSString *)stringByAppendingPathExtension:ext //為最後一段加上副檔名
-(NSString *)stringByDeletingLastPathComponent //刪除路徑的最後一段
-(NSString *)stringByDeletingPathExtension //刪除副檔名
-(NSString *)stringByExpandingTileInPath //將 ~ 展開為使用者主目錄
-(NSString *)stringByResolvingSymlinksInPath //解析路徑中的符號連結
-(NSString *)stringByStandardizingPath //標準化路徑(處理 ~、..、. 與符號連結)
NSString* NSUserName(void) //回傳目前使用者登入名稱
NSString* NSFullUserName(void) //回傳完整使用者名稱
NSString* NSHomeDirectory(void) //回傳主目錄路徑
NSString* NSHomeDirectoryForUser(NSString* user) //回傳指定使用者的主目錄
NSString* NSTemporaryDirectory(void) //回傳可用於暫存檔案的目錄
Documents(NSDocumentDirectory):存放 App 相關資料檔案,可與 iTunes 共享存取,且會自動備份到雲端。
Library/Caches(NSCachesDirectory):存放 App 的支援檔案,保存重新啟動後需要的資訊,iTunes 不會備份此目錄。
tmp(NSTemporaryDirectory()):存放暫存檔案,App 不再需要時應主動刪除。
Library/Preferences:存放偏好設定檔,通常以 NSUserDefaults 進行讀寫。
以下示範刪除 tmp 目錄下的所有檔案:
NSString *imageDir = [NSString stringWithFormat:@"%@", NSTemporaryDirectory()];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray* array = [fileManager contentsOfDirectoryAtPath:imageDir error:nil];
for (int j = 0; j < [array count]; j++) {
[fileManager removeItemAtPath:[NSString stringWithFormat:@"%@%@", imageDir, [array objectAtIndex:j]] error:nil];
}