读取文件内容到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 ,