IOS文件的简单读写实例详解
程序员文章站
2023-12-19 13:11:34
ios文件的简单读写实例详解
数组(可变与不可变)和字典(可变与不可变)中元素对象的类型,必须是nsstring,nsarray,nsdictionary,nsdata,...
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); }
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!