【iOS】如何判断⽂本⽂件的字符编码格式总体思路:
遍历所有的字符编码,能正确读取输出转换的就是⽂本⽂件的编码格式。
代码如下:
//
//  main.m
//  检测⽂本字符编码格式的⼩技巧
//
//  Created by 杜⼦兮 (duzixi) on 14-6-21.
//  Copyright (c) 2014年 lanou3g All rights reserved.
//
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSArray *arrEncoding = @[@(NSASCIIStringEncoding),
@(NSNEXTSTEPStringEncoding),
@(NSJapaneseEUCStringEncoding),
@(NSUTF8StringEncoding),
@(NSISOLatin1StringEncoding),
@(NSSymbolStringEncoding),
@(NSNonLossyASCIIStringEncoding),
@(NSShiftJISStringEncoding),
unicode文件格式
@(NSISOLatin2StringEncoding),
@(NSUnicodeStringEncoding),
@(NSWindowsCP1251StringEncoding),
@(NSWindowsCP1252StringEncoding),
@(NSWindowsCP1253StringEncoding),
@(NSWindowsCP1254StringEncoding),
@(NSWindowsCP1250StringEncoding),
@(NSISO2022JPStringEncoding),
@(NSMacOSRomanStringEncoding),
@(NSUTF16StringEncoding),
@(NSUTF16BigEndianStringEncoding),
@(NSUTF16LittleEndianStringEncoding),
@(NSUTF32StringEncoding),
@(NSUTF32BigEndianStringEncoding),
@(NSUTF32LittleEndianStringEncoding)
];
NSArray *arrEncodingName = @[@"NSASCIIStringEncoding",
@"NSNEXTSTEPStringEncoding",
@"NSJapaneseEUCStringEncoding",
@"NSUTF8StringEncoding",
@"NSISOLatin1StringEncoding",
@"NSSymbolStringEncoding",
@"NSNonLossyASCIIStringEncoding",
@"NSShiftJISStringEncoding",
@"NSISOLatin2StringEncoding",
@"NSUnicodeStringEncoding",
@"NSWindowsCP1251StringEncoding",
@"NSWindowsCP1252StringEncoding",
@"NSWindowsCP1253StringEncoding",
@"NSWindowsCP1254StringEncoding",
@"NSWindowsCP1250StringEncoding",
@"NSWindowsCP1250StringEncoding",
@"NSISO2022JPStringEncoding",
@"NSMacOSRomanStringEncoding",
@"NSUTF16StringEncoding",
@"NSUTF16BigEndianStringEncoding",
@"NSUTF16LittleEndianStringEncoding",
@"NSUTF32StringEncoding",
@"NSUTF32BigEndianStringEncoding",
@"NSUTF32LittleEndianStringEncoding"
];
for (int i = 0 ; i < [arrEncoding count]; i++) {
unsigned long encodingCode = [arrEncoding[i] unsignedLongValue];
NSLog(@"(%@)", arrEncodingName[i]);
NSError *error = nil;
NSString *filePath = @"/Users/dlios1/l"; // <---这⾥是要查看的⽂件路径
NSString *aString = [NSString stringWithContentsOfFile:filePath encoding:encodingCode  error:&error];            NSLog(@"Error:%@", [error localizedDescription]);
NSData *data = [aString dataUsingEncoding:encodingCode];
NSString *string = [[NSString alloc] initWithData:data encoding:encodingCode];
NSLog(@"%@", string);
/*
// 如果有必要,还可以把⽂件创建出来再测试
[string writeToFile:[NSString stringWithFormat:@"/Users/dlios1/Desktop/%@.xml", arrEncodingName[i]]                    atomically:YES
encoding:encodingCode
error:&error];
*/
}
}
return 0;
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。