2011-03-11 58 views

回答

6

您可以使用stringWithContentsOfFile:usedEncoding:error:,除了新字符串之外,还会返回使用的编码。

我应该注意到,这本质上是一个启发式过程 - 并不总是可以确定文件的字符编码。

+0

谢谢丹尼尔。 :) – Rizki 2011-03-11 07:53:53

1

一些文本文档在我的项目中显示乱码,所以我需要知道文本文件的编码,以更改其编码,让它可以被人类读取。

我发现这一点: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");