IOS文件的简单读写实例详解 数组(可变与不可变)和字典(可变与不可变)中元素对象的类型,必须是NSString,NSArray,NSDictionary,NSData,否则不能直接写入文件 #pragma mark---NSString的写入与读取--- /
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); }
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!