1
NSString *path =[[NSBundle mainBundle]pathForResource:@"1025626909" ofType:@"txt"];
NSStringEncoding enc;
NSError *error;
NSString *pageSource = [[NSString alloc] initWithContentsOfFile:path usedEncoding:&enc error:&error];
NSLog(@"==%@",pageSource);
NSLog(@"==%@",[error description]);

above code output this:</p>

2013-09-16 17:40:08.843 encodingTest[3350:c07] ==(null)
2013-09-16 17:40:08.846 encodingTest[3350:c07] ==Error Domain=NSCocoaErrorDomain Code=264 "The operation couldn’t be completed. (Cocoa error 264.)" UserInfo=0x71a5af0 {NSFilePath=/Users/dayu/Library/Application Support/iPhone Simulator/6.1/Applications/A33DE8D6-D64B-4791-ADB6-1AB4B35B743A/encodingTest.app/1025626909.txt  

I can't get the txt file's content,hope superman come help me 。。。。。</p>

I find the file I found this file encoding is GB2312 by other means,then i used the kCFStringEncodingGB_2312_80 code . There is no effect 。。。</p>

4

3 回答 3

4

错误 264 表示NSString无法确定文件的编码;因此需要告诉编码是什么,可能是 UTF-8:

NSString *pageSource = [[NSString alloc] initWithContentsOfFile:path
                                                       encoding:NSUTF8StringEncoding
                                                          error:&error];

为了找到错误 264 的含义,我查看了FoundationErrors.h

NSFileReadUnknownStringEncodingError NS_ENUM_AVAILABLE(10_5, 2_0) = 264, // Read error (string encoding of file contents could not be determined)

find我使用以下命令在我的 Xcode 应用程序内容中找到了它:

$ cd /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform
$ find . -name \*.h -exec fgrep -l 264 {} \;
./Developer/SDKs/iPhoneOS6.1.sdk/System/Library/Frameworks/AVFoundation.framework/Headers/AVAssetExportSession.h
(lots of others deleted)
./Developer/SDKs/iPhoneOS6.1.sdk/System/Library/Frameworks/Foundation.framework/Headers/FoundationErrors.h
于 2013-09-16T10:15:22.147 回答
0

我认为问题是usedEncoding的参数可能使用NSUTF8StringEncoding,那么你可能会得到txt文件的内容。

于 2013-09-16T10:17:41.360 回答
0

让我说说为什么。。。因为我希望 NSLog txt 文件的所有内容一次。那总是返回null。所以我把txt文件的一小部分,然后我得到了正确的内容......你知道,当我看到这个结果时我很高兴。
NSStringEncoding enc2 = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000); NSString *textFile = [NSString stringWithContentsOfFile:path encoding:enc2 error:&error];

于 2013-09-17T07:55:21.300 回答