读取文件内容到NSString
读取文件内容到nsstring,我使用以下代码
[cpp]
nsstring *filepath = [[[nsbundle mainbundle] resourcepath] stringbyappendingpathcomponent:@"push实现.txt"];
nserror* err=nil;
nsstring* mtxt=[nsstring stringwithcontentsoffile:filepath encoding:nsutf8stringencoding error:&err];
nslog(@"err:%@",err);
nslog(@"filepath:%@",filepath);
nslog(@"mtxt:%@",mtxt);
nsstring *filepath = [[[nsbundle mainbundle] resourcepath] stringbyappendingpathcomponent:@"push实现.txt"];
nserror* err=nil;
nsstring* mtxt=[nsstring stringwithcontentsoffile:filepath encoding:nsutf8stringencoding error:&err];
nslog(@"err:%@",err);
nslog(@"filepath:%@",filepath);
nslog(@"mtxt:%@",mtxt);
出错了,log为:
[plain]
2013-05-23 12:35:36.374 paging[26149:11303] err:error domain=nscocoaerrordomain code=261 "the operation couldn’t be completed. (cocoa error 261.)" userinfo=0x8868b00 {nsfilepath=/users/ericyang/library/application support/iphone simulator/6.1/applications/a3d216e7-dc10-48c3-ad40-302573d8c069/paging.app/push实现.txt, nsstringencoding=4}
2013-05-23 12:35:36.375 paging[26149:11303] filepath:/users/ericyang/library/application support/iphone simulator/6.1/applications/a3d216e7-dc10-48c3-ad40-302573d8c069/paging.app/push实现.txt
2013-05-23 12:35:36.375 paging[26149:11303] mtxt:(null)
2013-05-23 12:35:36.374 paging[26149:11303] err:error domain=nscocoaerrordomain code=261 "the operation couldn’t be completed. (cocoa error 261.)" userinfo=0x8868b00 {nsfilepath=/users/ericyang/library/application support/iphone simulator/6.1/applications/a3d216e7-dc10-48c3-ad40-302573d8c069/paging.app/push实现.txt, nsstringencoding=4}
2013-05-23 12:35:36.375 paging[26149:11303] filepath:/users/ericyang/library/application support/iphone simulator/6.1/applications/a3d216e7-dc10-48c3-ad40-302573d8c069/paging.app/push实现.txt
2013-05-23 12:35:36.375 paging[26149:11303] mtxt:(null)
找到原因,是编码问题,我的文件应该是gbk的,修改代码:
[cpp]
nsstring *filepath = [[[nsbundle mainbundle] resourcepath] stringbyappendingpathcomponent:@"push实现.txt"];
unsigned long encode = cfstringconvertencodingtonsstringencoding(kcfstringencodinggb_18030_2000);
nsdata *responsedata = [nsdata datawithcontentsoffile:filepath];
nsstring *mtxt = [[nsstring alloc] initwithdata:responsedata encoding:encode];
nslog(@"filepath:%@",filepath);
nslog(@"mtxt:%@",mtxt);
nsstring *filepath = [[[nsbundle mainbundle] resourcepath] stringbyappendingpathcomponent:@"push实现.txt"];
unsigned long encode = cfstringconvertencodingtonsstringencoding(kcfstringencodinggb_18030_2000);
nsdata *responsedata = [nsdata datawithcontentsoffile:filepath];
nsstring *mtxt = [[nsstring alloc] initwithdata:responsedata encoding:encode];
nslog(@"filepath:%@",filepath);
nslog(@"mtxt:%@",mtxt);
ok,正常打印。
下一篇: iOS开发之应用首次启动显示用户引导