IOS-txt文件UTF8、UTF16格式
在- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions中添加如下测试:
NSString* path = [[NSBundlemainBundle] pathForResource:@"textfile"ofType:@"txt"];
NSStringEncoding enc = NSUTF8StringEncoding; // this is a lie, so an error will result later
NSError* err;
// attempt to load a text file while specifying the wrong encoding
NSString* s = [NSStringstringWithContentsOfFile:path encoding:enc error:&err];
// at this point, s is nil as a signal that things went wrong, and err is a meaningful NSError
if (nil == s) // could also say if (!s)
{
NSLog(@"We got an error, as expected; it says:\n\"%@\"", [err localizedDescription]);
}
else
{
NSLog(@"everything went just fine; the text file says:\n%@", s);
// change NSUTF8StringEncoding to NSUTF16StringEncoding to get this message!
}
显示的提示信息:(此txt文档是UTF16格式的,使用UTF8读不出来)
We got an error, as expected; it says:
"The operation couldn’t be completed. (Cocoa error 261.)"
改为NSUTF16StringEncoding 后即可读出数据:
everything went just fine; the text file says:
This file in UTF16 encoding, but the app is going to claim it's UTF8.
TXT格式有四种编码:ANSI,Unicode,Unicode big endian,UTF-8。