iOS學習之檔案管理工具(NSFileManager)和檔案對接器(NSFileHandle),
1、檔案管理工具(NSFileManager) 1> 主要作用及功能方法
2> 建立檔案夾
建立所需的方法在標頭檔的聲明:
/* createDirectoryAtPath:withIntermediateDirectories:attributes:error: creates a directory at the specified path. If you pass 'NO' for createIntermediates, the directory must not exist at the time this call is made. Passing 'YES' for 'createIntermediates' will create any necessary intermediate directories. This method returns YES if all directories specified in 'path' were created and attributes were set. Directories are created with attributes specified by the dictionary passed to 'attributes'. If no dictionary is supplied, directories are created according to the umask of the process. This method returns NO if a failure occurs at any stage of the operation. If an error parameter was provided, a presentable NSError will be returned by reference. This method replaces createDirectoryAtPath:attributes: */
// 參數1:建立的檔案夾的路徑
// 參數2:是否建立媒介的布爾值,一般為YES
// 參數3: 屬性,沒有就置為nil
// 參數4: 錯誤資訊- (BOOL)createDirectoryAtPath:(NSString *)path withIntermediateDirectories:(BOOL)createIntermediates attributes:(nullable NSDictionary<NSString *, id> *)attributes error:(NSError **)error NS_AVAILABLE(10_5, 2_0);
執行個體代碼:
// 建立對象 NSFileManager *manager = [NSFileManager defaultManager]; // 建立路徑 NSString *path = NSHomeDirectory(); path = [path stringByAppendingPathComponent:@"test/myApp"]; NSLog(@"%@", path); NSError *error = nil; // 建立檔案夾 BOOL success = [manager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error]; NSLog(@"success = %d,error = %@", success,error);
2> 向檔案夾中添加檔案
內容寫入方法在標頭檔的聲明:
// 參數1:要寫入內容的檔案的檔案路徑// 參數2:一個BOOL值,一般為YES// 參數3: 編碼方式,一般為UTF8// 參數4:錯誤資訊- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile encoding:(NSStringEncoding)enc error:(NSError **)error;
執行個體代碼:
//向檔案夾中添加字串 path = [path stringByAppendingPathComponent:@"zifucuan.txt"]; //初始化一個字串 NSString *string = @"hello"; BOOL success1 = [string writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil]; if (success1) { NSLog(@"成功:%@",path); }else{ NSLog(@"失敗"); }
3> 刪除檔案夾中檔案
刪除檔案方法在標頭檔的聲明:
// 參數1:路徑// 參數2:錯誤資訊- (BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error NS_AVAILABLE(10_5, 2_0);
執行個體代碼:
// 刪除path目錄下的所有檔案 [manager removeItemAtPath:path error:nil];
4> 檔案移動
檔案移動方法在標頭檔的聲明:
// 參數1:要移動的檔案路徑// 參數2:要移動到的檔案路徑(目的地)// 參數3:錯誤資訊- (BOOL)moveItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error NS_AVAILABLE(10_5, 2_0);
執行個體代碼:
NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; // 建立一個檔案夾 NSString *copyPath = [documentPath stringByAppendingPathComponent:@"備份/test.txt"]; // stringByDeletingLastPathComponent 刪除最後一個路徑 [manager createDirectoryAtPath:[copyPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil]; // 定義一個字串 NSString *testStr = @"Hello World"; NSData *data = [testStr dataUsingEncoding:NSUTF8StringEncoding]; // 將內容寫入檔案 [manager createFileAtPath:copyPath contents:data attributes:nil]; // 建立一個toPath NSString *toPath = [documentPath stringByAppendingPathComponent:@"hello/copyTest.txt"]; // 建立一個移動到的檔案夾及檔案 [manager createDirectoryAtPath:[toPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil]; BOOL result = [manager moveItemAtPath:copyPath toPath:toPath error:nil]; NSLog(@"result = %d", result);
5> 檔案copy(拷貝)
檔案copy(拷貝)方法在標頭檔的聲明:
// 參數1:要拷貝的檔案路徑
// 參數2:要拷貝到的檔案路徑(目的地)
// 參數3:錯誤資訊
- (BOOL)copyItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error NS_AVAILABLE(10_5, 2_0);
執行個體代碼:
// 路徑使用上面的路徑[manager copyItemAtPath:copyPath toPath:toPath error:nil];
2、檔案夾處理器(NSFileHandle) 1> 概述
1).檔案對接並擷取一個NSFileHandle對象.
2).讀寫操作
3).關閉對接
注意:NSFileHandle 類並沒有提供建立檔案的功能。必須使用 NSFileManager 方法來建立檔案。因此,在使用表中的方法時,都是保證檔案已經存在,否則返回nil.
2> 功能方法
3> 使用NSFileHandle向檔案夾追加內容
// 參數為檔案路徑+ (nullable instancetype)fileHandleForUpdatingAtPath:(NSString *)path;
// 搜尋到檔案內容的末尾- (unsigned long long)seekToEndOfFile;
// 建立handle對象 NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:path]; // 搜尋到常值內容末尾 [fileHandle seekToEndOfFile]; NSString *appendStr = @"我是後來的"; NSData *appendData = [appendStr dataUsingEncoding:NSUTF8StringEncoding]; // 將資料寫入到對接起 [fileHandle writeData:appendData]; // 關閉對接起 [fileHandle closeFile];
4> 定位元據
// 參數為檔案路徑
+ (nullable instancetype)fileHandleForReadingAtPath:(NSString *)path;
@property (readonly, copy) NSData *availableData;
// 參數為一個和檔案長度有關的數值- (void)seekToFileOffset:(unsigned long long)offset;
- (NSData *)readDataToEndOfFile;
執行個體代碼:
// 將“123456”寫入file2.txt檔案夾中 NSString * content = @"123456"; NSString * filePath2 = [documentPath stringByAppendingPathComponent:@"file2.txt"]; [fileManager createFileAtPath:filePath2 contents:[content dataUsingEncoding:NSUTF8StringEncoding] attributes:nil]; // 通過fileHandle讀取 fileHandle = [NSFileHandle fileHandleForReadingAtPath:filePath2]; // 擷取資料長度 NSUInteger length = [[fileHandle availableData] length]; // 設定檔案的位移量為檔案的一半 [fileHandle seekToFileOffset:length/2.0]; // 從檔案的位移量位置讀取到最後 NSData * data = [fileHandle readDataToEndOfFile]; [fileHandle closeFile]; // 列印讀取的字串 NSString * string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@",string);