stringWithContentsOfFile仅适用于NSUTF16StringEncoding

时间:2014-06-21 02:10:18

标签: ios objective-c cocoa

我试图在iOS中读取.csv文件,当我使用NSUTF8StringEncoding时,它会打印null - 当我使用NSUTF16StringEncoding时,它会将我的文件打印为中文字符..任何人都可以告诉我这里有什么问题吗?我已将.csv拖入主项目目录,并将文件删除。这是我的示例代码:

 NSError *error;
NSString* filePath = [[NSBundle mainBundle] pathForResource:@"Crane_Data" ofType:@"csv"];
NSString *fileData = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
NSLog(@"TEST");
NSLog(@"%@",fileData);
NSLog(@"TEST");

使用以下错误测试后

 if (!fileData) NSLog(@"%@", error);

我用NSUTF8得到了这个

2014-06-20 22:20:57.351 CollectionView[6084:390557] Error Domain=NSCocoaErrorDomain Code=261 "The operation couldn’t be completed. (Cocoa error 261.)" UserInfo=0xaf5a7b0 {NSFilePath=/Users/Dylan/Library/Developer/CoreSimulator/Devices/D3F54177-0F08-47A5-9FE0-785E2AF0691A/data/Containers/Bundle/Application/81942FA8-BB67-4E8D-826E-7D1A445DD9B0/CollectionView.app/Crane_Data.csv, NSStringEncoding=4}

使用NSUTF16

在控制台上没有打印错误

1 个答案:

答案 0 :(得分:1)

编码是平面ASCII:

我从注释中获取了字节并将其格式化为char字符串,然后创建了一个NSString:

char* bytes = "\x66\x6f\x72\x74\x75\x6e\x65\x5f\x69\x64\x2c\x66\x6f\x72\x74\x75\x6e\x65\x5f\x61\x63\x74\x2c\x66\x6f\x72\x74\x75\x6e\x65\x5f\x74\x79\x70\x65\x2c\x66\x6f\x72\x74\x75\x6e\x65\x5f\x72\x6f\x6f\x74\x2c\x66\x6f\x72\x74\x75\x6e\x65\x5f\x73\x74\x72\x69\x6e\x67\x2c\x66\x6f\x72\x74\x75\x6e\x65\x5f\x64\x65\x73\x63\x72\x69\x70\x74\x69\x6f\x6e\x0d\x31\x2c\x31\x2c\x63\x6f\x6d\x70\x6f\x73\x69\x74\x69\x6f\x6e\x2c\x70\x2c\x4d\x61\x6b\x65\x20\x61\x6e\x20\x6f\x72\x69\x67\x61\x6d\x69\x20\x63\x72\x61\x6e\x65\x20\x2c\x0d\x32\x2c\x31\x2c\x63\x6f\x6d\x70\x6f\x73\x69\x74\x69\x6f\x6e\x2c\x70\x2c\x57\x72\x69\x74\x65\x20\x6f\x6e\x65\x20\x6c\x69\x6e\x65\x20\x6f\x66\x20\x73\x6f\x6d\x65\x74\x68\x69\x6e\x67\x2e\x2c\x54\x68\x69\x73\x20\x63\x6f\x6d\x70\x6f\x73\x69\x74\x69\x6f\x6e\x20\x63\x68\x61\x6c\x6c\x65\x6e\x67\x65\x20\x69\x73\x20\x69\x6e\x74\x65\x6e\x64\x65\x64\x20\x74\x6f\x20\x62\x65\x20\x63\x72\x65\x61\x74\x69\x76\x65\x2e\x20\x49\x74\x20\x63\x61\x6e\x6e\x6f\x74\x20\x62\x65\x20\x61\x20\x6c\x00";
NSUInteger bytesLength = strlen(bytes);
NSString *string = [[NSString alloc] initWithBytes:bytes length:bytesLength encoding:NSASCIIStringEncoding];
NSLog(@"string: %@", string);

NSLog输出:

  

的字符串:   fortune_id,fortune_act,fortune_type,fortune_root,fortune_string,fortune_description
          1,1,组成,p,制作折纸鹤,
          2,1,组成,p,写一行的东西。,这个构图挑战是有创意的。它不可能是一个

以下是初步回复:
如果是utf-16,有三种可能性:
NSUTF16StringEncoding
NSUTF16BigEndianStringEncoding
NSUTF16LittleEndianStringEncoding.
试试这三个。

如果失败则获取数据:
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
然后记录下来:
NSLog(@"fileData: %@", fileData);
发布前100个字节。找出格式应该很容易 如果你有这些信息,也要发布它应该是什么。