在Java中可以這樣獲取可用編碼:
SortedMap<String, Charset> availableCharsets = Charset.availableCharsets();
Vector allEncodes = new Vector();
for (Map.Entry<String, Charset> entry : availableCharsets.entrySet()) {
allEncodes.add(entry.getKey());
}
然後這樣讀取文件:
Reader in = new InputStreamReader(new FileInputStream(aPath), allEncodes.get(0) );
那麼在objective-c中怎麼實現類似的功能?
我給的代碼有點類似Java.不過你要完善其中的readingError變量。核心代碼是avaiableStringEncodings
.
NSMutableArray *arrayOfEncodings = [[NSMutableArray alloc] init];
const NSStringEncoding *encodings = [NSString availableStringEncodings];
while (*encodings != 0){
[arrayOfEncodings addObject:[NSNumber numberWithInt:*encodings]];
encodings++;
}
NSError *readingError = nil;
NSString yourPath = @"some path you want";
NSData *data = [[NSData alloc] initWithContentsOfFile:yourPath options:NSDataReadingUncached error:&readingError];
NSStringEncoding firstEncoding = (NSStringEncoding) [((NSNumber *) [arrayOfEncodings objectAtIndex:0]) intValue];
NSString *myString = [[NSString alloc] initWithData:data encoding:firstEncoding];