iOS----获取txt内容(不同种类的编码格式)转换为需要的类型

字符串类型

数组类型

字典类型

编码格式UTF8时,使用该方法可以实现转换为字典类型信息

    //获取文件路径
    NSString *path  = [NSBundle.mainBundle pathForResource:@"home_2" ofType:@"txt"];
    //文件内容转换成字符串类型
    NSString* str=[[NSString alloc] initWithContentsOfFile:path];
    //字符串内容转换为NSData类型
    NSData *data =  [str dataUsingEncoding:NSUTF8StringEncoding];
    //NSData类型转换为字典类型
    NSDictionary * dic =  [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    //打印字典信息
    NSLog(@"dic%@",dic);

编码格式为UTF8时,使用该方法可以实现转换为字典类型信息

    NSString *path  = [NSBundle.mainBundle pathForResource:@"home_1" ofType:@"txt"];
    NSData *data =  [NSData dataWithContentsOfFile:path];
    NSDictionary * dic =  [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    NSLog(@"%@",dic);

编码格式为GBK时,使用该方法可以实现转换为字典类型信息

思路:先将gbk格式的字符串转换成utf8格式的字符串,再使用。
      NSString *path  = [NSBundle.mainBundle pathForResource:self.textArray[self.num] ofType:@"txt"];
    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    //文件内容转换成字符串类型
    NSString* str = [[NSString alloc] initWithContentsOfFile:path encoding:enc error:nil];
     NSLog(@"%@",str);
    NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
    NSLog(@"%@",dic);

//获取txt文件中的内容,且将内容转换为需要的类型
//首先获取到文件路径
//转换为需要的格式

// //编码格式有误时,使用该方法可以实现转换为字典类型信息
// //获取文件路径
// NSString path = [NSBundle.mainBundle pathForResource:@"home_2" ofType:@"txt"];
// //文件内容转换成字符串类型
// NSString
str=[[NSString alloc] initWithContentsOfFile:path];
// //字符串内容转换为NSData类型
// NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
// //NSData类型转换为字典类型
// NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
// //打印字典信息
// NSLog(@"dic%@",dic);

NSString *path1  = [NSBundle.mainBundle pathForResource:@"home" ofType:@"txt"];
NSDictionary* dic1 = [NSDictionary dictionaryWithContentsOfFile:path1];
NSLog(@"dic1%@",dic1);

你可能感兴趣的:(iOS----获取txt内容(不同种类的编码格式)转换为需要的类型)