iphone存储然后从Documents文件夹中读取文件

use*_*712 1 iphone file objective-c

这一定很简单,但我想把一个文件放在Documents文件夹中,该文件夹在启动时读入.我有关于如何阅读并确认其查找正确目录的代码.但是我保存在xcode的Resources文件夹中的文件RootList.txt存储在Root.app文件夹下,而Documents文件夹是空的.因此,当我启动应用程序时它找不到此文件.

有没有办法确保文件在启动时内置到Documents目录中(我在模拟器中运行它).

替代方案是一个工作正常的plist但我只是好奇.

ahm*_*rah 7

在这些情况下,我遵循这种方法:

首先将您的RootList.txt保存在xCode的Resources文件夹中.您的Documents文件夹中没有任何内容.

在applicationDidLaunch调用的开头,执行:

NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *path = [docsDirectory stringByAppendingPathComponent:@"RootList.txt"];
if(![fileManager fileExistsAtPath:path])
{
NSData *data = [NSData dataWithContentsOfFile:[[[NSBundle mainBundle] resourcePath] stringByAppendingString:@"/RootList.txt"]];
[data writeToFile:path atomically:YES];
}
Run Code Online (Sandbox Code Playgroud)

现在,您的文件在启动时位于Documents文件夹中.