iOS converts strings to txt files

String to txt document

Call the txt document where it is used. Here I am using the string converted from the recording file. It can be changed according to the actual project.

NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"testLogs2.wav"ofType:nil]; // 获取项目里面的文件
NSData *data1 = [NSData dataWithContentsOfFile:bundlePath];
NSString *base64String = [data1 base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
[self writeToFileWithTxt:base64String];// 将字符串写入沙盒 转成txt。这个地方可以是任何的字符串。

Write the file to the sandbox and form a txt format document

- (void)writeToFileWithTxt:(NSString *)string{
    
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
    
    
        @synchronized (self) {
    
    
            //获取沙盒路径
            NSArray *paths  = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
            //获取文件路径
            NSString *theFilePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"testLogs2.txt"];
            //创建文件管理器
            NSFileManager *fileManager = [NSFileManager defaultManager];
            //如果文件不存在 创建文件
            if(![fileManager fileExistsAtPath:theFilePath]){
    
    
                NSString *str = @"日志开始记录\n";
                [str writeToFile:theFilePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
            }
            NSLog(@"所写内容=%@",string);
            NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:theFilePath];
            [fileHandle seekToEndOfFile];  //将节点跳到文件的末尾
            NSData* stringData  = [[NSString stringWithFormat:@"%@\n",string] dataUsingEncoding:NSUTF8StringEncoding];
            [fileHandle writeData:stringData]; //追加写入数据
            [fileHandle closeFile];
        }
    });
}

おすすめ

転載: blog.csdn.net/c1o2c3o4/article/details/117667271