NSFileHandle编写json数据格式
代码如下:
+ (void)writeToFile:(NSDictionary *)params filePath:(NSString *)path { NSData *jsonData = [self jsonToData:params]; NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:path]; if (fileHandle == nil) { NSLog(@"Failed to open file"); } // 获取文件内容末尾的']' [fileHandle seekToFileOffset:[fileHandle seekToEndOfFile] - 1]; NSData *endData = [fileHandle readDataToEndOfFile]; // 插入params [fileHandle seekToFileOffset:[fileHandle seekToEndOfFile] - 1]; [fileHandle writeData:jsonData]; // 数组数据分割符 NSData *diviData = [@"," dataUsingEncoding:NSUTF8StringEncoding]; [fileHandle seekToEndOfFile]; [fileHandle writeData:diviData]; // 在文件内容末尾添加结束标识符']' [fileHandle seekToEndOfFile]; [fileHandle writeData:endData]; //关闭文件 [fileHandle closeFile]; }
效果如图: