有人能告诉我如何用文件保存字节顺序标记(BOM)吗?例如,我保存一个文本文件,如下所示:
NSString *currentFileContent = @"This is a string of text to represent file content.";
NSString *currentFileName = @"MyFileName";
NSString *filePath = [NSString stringWithFormat:@"%@/%@.%@", [self documentsDirectory], currentFileName, rtf];
[currentFileContent writeToFile:filePath atomically:YES encoding:NSUTF16StringEncoding error:&error];我对BOM的理解是:
BOM字符是Unicode字符集中的“零宽度无中断空间”字符U+FEFF。
我有一个iPhone应用程序,允许用户将文本保存到RTF文件中。如果我使用NSUTF8StringEncoding,所有操作都很好,除非用户有双字节字符,如日语或中文。简单的答案似乎是用NSUTF16StringEncoding保存文件,这在最近的RTF规范中是允许的,但Microsoft只能在定义BOM的情况下才能自动打开UTF-16文件。
我希望,如果我可以设置一个通用的BOM,我将不需要识别用户的字符集,因为我没有办法知道什么是预先。但是他们仍然能够打开双字节字符的RTF文件.
谢谢你的建议或见解。
发布于 2011-06-23 22:27:31
如果您首先将字符串转换为数据,然后将数据写入文件,那么NSString的dataUsingEncoding:allowLossyConversion:将为您添加BOM。您可以按以下方式编写您的文件:
NSData *data = [currentFileContent dataUsingEncoding:NSUTF16StringEncoding];
[data writeToFile:filePath options:NSDataWritingAtomic error:&error];https://stackoverflow.com/questions/6460594
复制相似问题