1.获取到对应的文件夹
+ (NSString *)getLogFilePath{
NSString *documentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
//log.txt文件
documentsDir = [documentsDir stringByAppendingPathComponent:@"log.txt"];
return documentsDir;
}
2.判断对应文件是否存在,不存在则创建
NSString *documentsDir = [self getLogFilePath];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL isExit = [fileManager fileExistsAtPath:documentsDir];
//文件夹是否存在
if (!isExit) {
NSLog(@"log文件不存在");
[fileManager createFileAtPath:documentsDir contents:nil attributes:nil];
}
3.先读取文件中数据,然后将全部数据写入文件中
//先读取文件中内容
NSError *error;
NSString *content =[NSString stringWithContentsOfFile:documentsDir encoding:NSUTF8StringEncoding error:&error];
if (!error) {
NSLog(@"文件读取成功: %@",content);
}else{
NSLog(@"%@",error.localizedDescription);
}
if (content.length == 0 || [content isKindOfClass:[NSNull class]] || content == nil) {
NSLog(@"文件中无数据");
}else{
info = [NSString stringWithFormat:@"%@\n%@",content,info];
}
BOOL res = [info writeToFile:documentsDir atomically:YES encoding:NSUTF8StringEncoding error:nil];
if (res) {
NSLog(@"INFO写入成功");
}else {
NSLog(@"INFO写入失败");
}
网友评论