如何在iOS上以编程方式创建.txt文件 [英] How to create a .txt file programmatically on iOS

查看:499
本文介绍了如何在iOS上以编程方式创建.txt文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名新的iOS开发人员.我想创建一个将在应用程序文件夹中自动创建新的* .txt文件的应用程序.我只能找到如何打开,关闭,保存,写入和读取的方法,而不能创建.如何创建新文件?谢谢.

I am a new iOS developer. I want to create an app that will auto-create new *.txt files in the app's folder. I could only find how to open, close, save, write, and read - not create. How can I create new files? Thanks.

推荐答案

使用以下代码在应用程序的Documents目录中写入/创建.txt文件.这应该是不言自明的.

Use the following code to write/create a .txt file in your app's Documents directory. It should be pretty self-explanatory.

NSError *error;
NSString *stringToWrite = @"1\n2\n3\n4";
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"myfile.txt"];
[stringToWrite writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];

并获取文本文件:

NSString *str = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
NSLog(@"%@", str);

这篇关于如何在iOS上以编程方式创建.txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆