iOS NSFileManager文件管理(沙盒)
OS因為沙盒機制,所以只能訪問通訊錄、相冊和App內的文件,下面就來說說如何進行文件管理。
App所產生的數據都存在于自己的沙盒中,一般沙盒都有3個文件:Documents、Library和tmp。
Documents: 這個目錄存放用戶數據。存放用戶可以管理的文件;iTunes備份和恢復的時候會包括此目錄。
Library: 主要使用它的子文件夾,我們熟悉的NSUserDefaults就存在于它的子目錄中。
Library/Caches: 存放緩存文件,iTunes不會備份此目錄,此目錄下文件不會在應用退出刪除,“刪除緩存”一般指的就是清除此目錄下的文件。
Library/Preferences: NSUserDefaults的數據存放于此目錄下。
tmp: App應當負責在不需要使用的時候清理這些文件,系統在App不運行的時候也可能清理這個目錄。
獲取App沙盒根路徑:
NSString *dirHome = NSHomeDirectory();獲取Documents目錄路徑:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0];獲取Library目錄路徑
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES); NSString *libraryDirectory = [paths objectAtIndex:0];獲取Library/Caches目錄路徑
NSArray *cacPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); NSString *cachePath = [cacPath objectAtIndex:0];獲取Tmp目錄路徑
NSString *tmpDirectory = NSTemporaryDirectory();創建文件夾/目錄(返回創建結果)
- (BOOL)createDir:(NSString *)fileName {NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);NSString *documentsDirectory = [paths objectAtIndex:0];NSString *path = [NSString stringWithFormat:@"%@/%@",documentsDirectory,fileName];NSFileManager *fileManager = [NSFileManager defaultManager];BOOL isDir;// 先判斷目錄是否存在,不存在才創建if (![fileManager fileExistsAtPath:path isDirectory:&isDir]) {BOOL res = [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];return res;} else {return NO;} }創建文件(返回創建結果)
- (BOOL)createFile:(NSString *)path {NSFileManager *fileManager = [NSFileManager defaultManager];// 在傳入的路徑下創建test.c文件NSString *testPath = [path stringByAppendingPathComponent:@"test.c"];// 通過data創建數據BOOL res = [fileManager createFileAtPath:testPath contents:nil attributes:nil]; [fileManager createFileAtPath:testPath contents:data attributes:nil];return res; }寫數據到文件(返回寫入結果)
- (BOOL)writeFile:(NSString *)path {NSString *testPath = [path stringByAppendingPathComponent:@"test.c"];NSString *content = @"將數據寫入到文件!";BOOL res = [content writeToFile:testPath atomically:YES encoding:NSUTF8StringEncoding error:nil];return res; }讀文件數據
- (void)readFile:(NSString *)path {// 方法1:NSData *data = [NSData dataWithContentsOfFile:path]; NSString *content = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);//方法2:NSString *content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];NSLog(@"文件讀取成功: %@", content); }文件屬性
- (void)fileAttriutes:(NSString *)path{ NSFileManager *fileManager = [NSFileManager defaultManager];NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:path error:nil];NSArray *keys;id key, value;keys = [fileAttributes allKeys];int count = [keys count];for (int i = 0; i < count; i++) {key = [keys objectAtIndex:i]; // 獲取文件名value = [fileAttributes objectForKey:key]; // 獲取文件屬性} }根據路徑刪除文件(返回刪除結果)
- (BOOL)deleteFileByPath:(NSString *)path {NSFileManager *fileManager = [NSFileManager defaultManager];BOOL res = [fileManager removeItemAtPath:path error:nil];return res;NSLog(@"文件是否存在: %@", [fileManager isExecutableFileAtPath:path]?@"YES":@"NO"); }根據文件名刪除文件
- (BOOL)deleteFileByName:(NSString *)name {NSFileManager *fileManager = [NSFileManager defaultManager];// getLocalFilePath方法在下面[fileManager removeItemAtPath:[self getLocalFilePath:fileName] error:nil]; }根據路徑復制文件
+ (BOOL)copyFile:(NSString *)path topath:(NSString *)topath {BOOL result = NO;NSError *error = nil;result = [[NSFileManager defaultManager] copyItemAtPath:path toPath:topath error:&error];if (error) {NSLog(@"copy失敗:%@", [error localizedDescription]);}return result; }根據路徑剪切文件
+ (BOOL)cutFile:(NSString *)path topath:(NSString *)topath { BOOL result = NO;NSError *error = nil;result = [[NSFileManager defaultManager] moveItemAtPath:path toPath:topath error:&error];if (error) {NSLog(@"cut失敗:%@", [error localizedDescription]);}return result; }根據文件名獲取資源文件路徑
+ (NSString *)getResourcesFile:(NSString *)fileName {return [[NSBundle mainBundle] pathForResource:fileName ofType:nil]; }根據文件名獲取文件路徑
+ (NSString *)getLocalFilePath:(NSString *)fileName {NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"/Documents"]return [NSString stringWithFormat:@"%@/%@", path, fileName]; }根據文件路徑獲取文件名稱
+ (NSString *)getFileNameByPath:(NSString *)filepath {NSArray *array = [filepath componentsSeparatedByString:@"/"];if (array.count == 0) return filepath;return [array objectAtIndex:array.count-1]; }根據路徑獲取該路徑下所有目錄
+ (NSArray *)getAllFileByName:(NSString *)path {NSFileManager *defaultManager = [NSFileManager defaultManager];NSArray *array = [defaultManager contentsOfDirectoryAtPath:path error:nil];return array; }根據路徑獲取文件目錄下所有文件
+ (NSArray *)getAllFloderByName:(NSString *)path {NSFileManager *fileManager = [NSFileManager defaultManager];NSArray *fileAndFloderArr = [self getAllFileByName:path];NSMutableArray *dirArray = [[NSMutableArray alloc] init];BOOL isDir = NO;// 在上面那段程序中獲得的fileList中列出文件夾名for (NSString *file in fileAndFloderArr) {NSString *paths = [path stringByAppendingPathComponent:file];[fileManager fileExistsAtPath:paths isDirectory:(&isDir)];if (isDir) {[dirArray addObject:file];}isDir = NO;}return dirArray; }獲取文件及目錄的大小
+ (float)sizeOfDirectory:(NSString *)dir {NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:dir];NSString *pname;int64_t s = 0;while (pname = [direnum nextObject]) {//NSLog(@"pname %@",pname);NSDictionary *currentdict = [direnum fileAttributes];NSString *filesize = [NSString stringWithFormat:@"%@", [currentdict objectForKey:NSFileSize]];NSString *filetype = [currentdict objectForKey:NSFileType];if ([filetype isEqualToString:NSFileTypeDirectory]) continue;s = s + [filesize longLongValue];}return s*1.0; }重命名文件或目錄
+ (BOOL)renameFileName:(NSString *)oldName toNewName:(NSString *)newName {BOOL result = NO;NSError *error = nil;result = [[NSFileManager defaultManager] moveItemAtPath:[kDSRoot stringByAppendingPathComponent:oldName] toPath:[kDSRoot stringByAppendingPathComponent:newName] error:&error];if (error){NSLog(@"重命名失敗:%@", [error localizedDescription]);} return result; }讀取文件
+ (NSData *)readFileContent:(NSString *)filePath {return [[NSFileManager defaultManager] contentsAtPath:filePath]; }保存文件
+ (BOOL)saveToDirectory:(NSString *)path data:(NSData *)data name:(NSString *)newName {NSString *resultPath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@", newName]];return [[NSFileManager defaultManager] createFileAtPath:resultPath contents:data attributes:nil]; }總結
以上是生活随笔為你收集整理的iOS NSFileManager文件管理(沙盒)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring Tips: The Wav
- 下一篇: 【12月原创】RT-thread - 柿