我想了解如何在Objective-C中确定文本文件的编码方式。您能否告诉我如何做到这一点?
我想了解如何在Objective-C中确定文本文件的编码方式。您能否告诉我如何做到这一点?
stringWithContentsOfFile:usedEncoding:error:
方法,它不仅返回新字符串,还返回所使用的编码方式。我的项目中有一些文本文件显示的是乱码,所以我需要知道这些文件的编码方式,改变它们的编码方式,使得人类可以读懂它们。
我找到了这个链接:http://lists.w3.org/Archives/Public/www-validator/2002Aug/0084.html 并且使用OC来重新编写代码,这对我很有帮助:
NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *sourceFilePath = [documentPath stringByAppendingPathComponent:@"fileName.txt"];
NSFileHandle *sourceFileHandle = [NSFileHandle fileHandleForReadingAtPath:sourceFilePath];
NSData *begainData = [sourceFileHandle readDataOfLength:3];
Byte *bytes = (Byte *)[begainData bytes];
if (bytes[0] == 0xff
&& bytes[1] == 0xfe
&& (begainData.length < 4
|| bytes[2] != 0
|| bytes[3] != 0
)
)
{
NSLog(@"unicode");
}
if (bytes[0] == 0xfe
&& bytes[1] == 0xff
)
NSLog(@"BigEndianUnicode");
if (bytes[0] == 0xef && bytes[1] == 0xbb && bytes[2] == 0xbf)
NSLog(@"UTF8");
if (bytes[0] == 0x2b && bytes[1] == 0x2f && bytes[2] == 0x76)
NSLog(@"UTF7");
if (bytes[0] == 0xff && bytes[1] == 0xfe && bytes[2] == 0 && bytes[3] == 0)
NSLog(@"UTF32");
if (begainData.length < 3)
NSLog(@"ascii");