2011-03-11 59 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");