IOS文件的簡單讀寫實例詳解
數組(可變與不可變)和字典(可變與不可變)中元素對象的類型,必須是NSString,NSArray,NSDictionary,NSData,否則不能直接寫入文件
#pragma mark---NSString的寫入與讀取--- //1:獲取路徑 NSString *docunments = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject]; //2:在該路徑下創建文件夾,文件夾名為字符串.txt docunments = [docunments stringByAppendingString:@"/字符串.txt"]; // NSLog(@"%@",docunments); //3:編寫文本內容 NSString *str = @"大家一起來"; //4:將文本寫入到"字符串.txt"中 /* writeToFile:文件路徑,在這裡是documents atomically:YES(若為YES,則保證了文件的原子性,即先創建一個臨時文件,直到文件內容寫入成功再導入目標文件(字符串.txt),為NO,直接寫入目標文件裡) encoding:編碼格式是個枚舉值 error:錯誤信息,一般為nil */ BOOL result = [str writeToFile:docunments atomically:YES encoding:NSUTF8StringEncoding error:nil]; if (result) { NSLog(@"我成功了"); }else{ NSLog(@"為啥失敗了"); } //讀取 /* stringWithContentsOfFile:路徑 encoding:編碼 error:nil,錯誤信息 */ NSString *newStr = [NSString stringWithContentsOfFile:docunments encoding:4 error:nil]; NSLog(@">>>>%@",newStr); /* .plist全名是:Property List,屬性列表文件,它是一種用來存儲串行化(當程序徹底退出後,對象就會隨之消亡,但是,我們希望有些東西需要記錄下來,以便於恢復,也可提升用戶體驗,而記錄的這個過程,就叫串行化)後的對象的文件。屬性列表文件的擴展名為.plist ,因此通常被稱為 plist文件。文件是xml格式的。 注意:plist文件通常用於存儲用戶設置,也可用於存儲捆綁信息 */ #pragma mark---NSArray的寫入與讀取 //獲取路徑 NSString *arrayDoc = [SandBox getDocuments]; //在arrayDoc下拼接文件名 NSString *arrPath = [arrayDoc stringByAppendingString:@"array.plist"]; //向數組中寫入數據 NSArray *array = @[@"25",@"55",@"05",@"5885"]; //將數組寫入文件 [array writeToFile:arrPath atomically:YES]; NSLog(@"數組存入路徑%@",arrPath); //讀取 NSArray *newArray = [NSArray arrayWithContentsOfFile:arrPath]; NSLog(@"讀取的文件:%@",newArray); #pragma mark--- 字典的寫入與讀取---- NSString *dicionaryDic = [SandBox getDocuments]; NSString *dicpath = [dicionaryDic stringByAppendingString:@"dictionary.plist"]; NSDictionary *dictionary = @{@"name":@"甲甲",@"age":@"18"}; [dictionary writeToFile:dicpath atomically:YES]; NSLog(@"字典存入路徑%@",dicpath); //讀取 NSDictionary *newdict = [NSDictionary dictionaryWithContentsOfFile:dicpath]; NSLog( @"讀取的字典文件%@",newdict); #pragma mark--- NSData---- NSString *DataPath = [[SandBox getDocuments]stringByAppendingString:@"Data.data"]; // NSString *string = @"丑八怪"; // NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding]; UIImage *image = [UIImage imageNamed:@"2"]; NSData *data = UIImageJPEGRepresentation(image, 0.5); [data writeToFile:DataPath atomically:YES]; NSLog(@"%@",DataPath); //讀取 NSData *newData = [NSData dataWithContentsOfFile:DataPath]; // NSString *new = [[NSString alloc]initWithData:newData encoding:4]; UIImage *new = [UIImage imageWithData:newData scale:1]; NSLog(@"%@",newData); NSLog(@"%@",new); }
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!