iOS 用string生成txt文件,并保存至本地
程序员文章站
2022-03-03 12:47:24
...
/** param string:文件内容 fileName:文件名 */ - (void)writeToTXTFileWithString:(NSString *)string fileName:(NSString *)fileName { dispatch_async(dispatch_get_global_queue(0, 0), ^{ @synchronized (self) { //获取沙盒路径 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES); //获取文件路径 NSString *fullName = [NSString stringWithFormat:@"%@.txt", fileName]; NSString *theFilePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:fullName]; //创建文件管理器 NSFileManager *fileManager = [NSFileManager defaultManager]; //如果文件不存在 创建文件 if(![fileManager fileExistsAtPath:theFilePath]){ [@"" writeToFile:theFilePath atomically:YES encoding:NSUTF8StringEncoding error:nil]; } NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:theFilePath]; [fileHandle seekToEndOfFile]; //将节点跳到文件的末尾 NSData* stringData = [[NSString stringWithFormat:@"%@\n",string] dataUsingEncoding:NSUTF8StringEncoding]; [fileHandle writeData:stringData]; //追加写入数据 [fileHandle closeFile]; } }); }