如何在iOS上以编程方式创建.txt文件

如何在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);