当前位置:首页 > 通信资讯 > 正文

ios 文件 读写(ios 写文件)

IOS文件的简单读写实例详解

数组(可变与不可变)和字典(可变与不可变)中元素对象的类型,必须是NSString,NSArray,NSDictionary,NSData,否则不能直接写入文件

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 #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); }

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

原文链接:http://www.jianshu.com/p/6e7894554409

如果您对该产品感兴趣,请填写办理(客服微信:xiaoxiongyidong)

为您推荐:

发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。