在Mac OS上新建一个rtf文件,然后指定通过NSString读取该文件乱码i问题
然后通过下面代码读取文件内容:
NSString *path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"rtf"];
NSError *error;
NSString *stringFromFileAtPath = [[NSString alloc]
initWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:&error];
if (stringFromFileAtPath == nil)
{
// an error occurred
NSLog(@"Error reading file at %@\n%@",path, [error localizedFailureReason]);
// implementation continues ...
}else
{
NSLog(@"stringFromFile is: %@",stringFromFileAtPath);
}
你会发现读取出来的不是utf-8的文字
解决方法:把文件test.rtf文件拖到xcode里面,然后右建--》open as--》 source code
把中文文字拷贝到里面,保存下。
[img]http://dl.iteye.com/upload/attachment/0068/3022/cdae63e7-501a-3ddd-9461-a01c81a49b74.png[/img]
二: 如果你要通过rtf来保存一个纯文本的信息,你可以指定编码。
打开mac下的文本编辑软件,随便输入几个字;然后在菜单栏上选择--》格式--》制作纯文本,保存的时候,就可以选择文本格式了。
然后通过下面代码读取文件内容:
NSString *path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"rtf"];
NSError *error;
NSString *stringFromFileAtPath = [[NSString alloc]
initWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:&error];
if (stringFromFileAtPath == nil)
{
// an error occurred
NSLog(@"Error reading file at %@\n%@",path, [error localizedFailureReason]);
// implementation continues ...
}else
{
NSLog(@"stringFromFile is: %@",stringFromFileAtPath);
}
你会发现读取出来的不是utf-8的文字
解决方法:把文件test.rtf文件拖到xcode里面,然后右建--》open as--》 source code
把中文文字拷贝到里面,保存下。
[img]http://dl.iteye.com/upload/attachment/0068/3022/cdae63e7-501a-3ddd-9461-a01c81a49b74.png[/img]
二: 如果你要通过rtf来保存一个纯文本的信息,你可以指定编码。
打开mac下的文本编辑软件,随便输入几个字;然后在菜单栏上选择--》格式--》制作纯文本,保存的时候,就可以选择文本格式了。