创建.json文件,并写入内容,在路径下能够找到创建的文件和里面有写入的内容,但是相同路径下获取文件,读取的内容是空的。下面是代码:
// ************ 创建文件 ************ /
// 创建文件管理器
NSFileManager *fileManager = [NSFileManager defaultManager];
// 获取document路径,括号中属性为当前应用程序独享
NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [directoryPaths objectAtIndex:0];
NSLog(@"document = %@", documentDirectory);
//定义记录文件全名以及路径的字符串filePath
NSString *filePath = [documentDirectory stringByAppendingPathComponent:@"my_js.json"];
NSLog(@"filePath = %@", filePath);
//查找文件,如果不存在,就创建一个文件
if (![fileManager fileExistsAtPath:filePath]) {
[fileManager createFileAtPath:filePath contents:nil attributes:nil];
}
// ************ 写入文件 ************ /
NSString *temp = @"Hello world";
//创建数据缓冲
NSMutableData *writer = [[NSMutableData alloc]init];
//将字符串添加到缓冲中
[writer appendData:[temp dataUsingEncoding:NSUTF8StringEncoding]];
[writer writeToFile:filePath atomically:YES];
// ************ 读取文件 ************ /
NSData *jsonData = [NSData dataWithContentsOfFile:filePath];
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
NSLog(@"读取文件 = %@", jsonObject);
使用NSString直接获取能够获取到。NSString *value = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
是在虚拟机上跑的,还是真机,如果是虚拟机,打开沙盒看一下,文件存在吗,内容存在吗,另外,总感觉你这个json不对啊,json的最外层应该只是{},[]这两种,你直接写个字符串不行吧
是在虚拟机上运行,文件路径下有“my_js.json”文件,并且有内容“Hello world”。就是读取时是nil!
json不应该是以key value形式存在的吗,得字典或者数组才可以转成json,然后解析出来用字典或者数组接着。。。是了,应该没错,欢迎指正