2

有人可以告诉我如何用文件保存字节顺序标记(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 字符集中的“ZERO WIDTH NO-BREAK SPACE”字符 U+FEFF。

我有一个 iPhone 应用程序,允许用户将文本保存到 RTF 文件。如果我使用 NSUTF8StringEncoding,一切正常,除非用户有双字节字符,例如日语或中文。简单的答案似乎是使用 NSUTF16StringEncoding 保存文件,这在最近的 RTF 规范中是允许的,除了 Microsoft Word 只能在定义 BOM 时自动打开 UTF-16 文件。

我希望如果我可以设置通用 BOM,我就不需要识别用户的字符集,因为我无法提前知道那是什么。但他们仍然可以打开带有双字节字符的 RTF 文件。

感谢您的建议或见解。

4

1 回答 1

1

如果您首先将字符串转换为数据,然后将数据写入文件,那么 NSStringdataUsingEncoding:allowLossyConversion:将为您添加 BOM。您可以按如下方式编写文件:

NSData *data = [currentFileContent dataUsingEncoding:NSUTF16StringEncoding];
[data writeToFile:filePath options:NSDataWritingAtomic error:&error];
于 2011-06-23T22:27:31.773 回答