我正在尝试在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在控制台上也没有打印错误

最佳答案

编码为平面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,composition,p,制作折纸鹤,
          2,1,composition,p,写一行东西。此构图挑战旨在发挥创造力。不能是我


以下是最初的回应:
如果是utf-16,则有三种可能性:
NSUTF16StringEncoding
NSUTF16BigEndianStringEncoding
NSUTF16LittleEndianStringEncoding.
尝试全部三个。

如果失败,则获取数据:
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
然后登录:
NSLog(@"fileData: %@", fileData);
这样发布前一百个字节。应该很容易弄清楚格式。
如果您知道该信息,也请张贴该信息。

关于ios - stringWithContentsOfFile仅适用于NSUTF16StringEncoding,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24337648/

10-12 03:35