临近春节了,这段时间比较忙,各种赶项目,没啥时间写博客。
/**
?*? @brief 追加写入数据到沙盒路径
?*
?*? @param string ? 要写入的字符串
?*? @param fileName 把数据写入文件的文件名
?*/
+(void)writefile:(NSString *)string fileName:(NSString *)fileName
{
? ? NSLog(@"fileName==%@",fileName);
? ? NSArray *paths? = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
? ? NSString *homePath = [paths objectAtIndex:0];
?? ?
? ? NSString *filePath = [homePath stringByAppendingPathComponent:fileName];
?? ?
? ? NSFileManager *fileManager = [NSFileManagerdefaultManager];
?? ?
? ? if(![fileManager fileExistsAtPath:filePath]) //如果不存在
? ? {
? ? ? ? NSLog(@"-------文件不存在,写入文件----------");
? ? ? ? NSError *error;
? ? ? ? if([string writeToFile:filePath atomically:YESencoding:NSUTF8StringEncodingerror:&error])
? ? ? ? {
? ? ? ? ? ? NSLog(@"------写入文件------success");
? ? ? ? }
? ? ? ? else
? ? ? ? {
?? ? ? ? ? ? NSLog(@"------写入文件------fail,error==%@",error);
? ? ? ? }
? ? }
? ? else//追加写入文件,而不是覆盖原来的文件
? ? {
? ? ? ? NSLog(@"-------文件存在,追加文件----------");
? ? ? ? NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
?? ? ? ?
? ? ? ? [fileHandle seekToEndOfFile];? //将节点跳到文件的末尾
?? ? ? ?
?? ? ? ?
? ? ? ? NSData* stringData? = [string dataUsingEncoding:NSUTF8StringEncoding];
?? ? ? ?
? ? ? ? [fileHandle writeData:stringData]; //追加写入数据
?? ? ? ?
? ? ? ? [fileHandle closeFile];
? ? }
}