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

时间:2010-02-04 20:34:35

标签: iphone objective-c file

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

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

替代方案是一个可以正常工作的plist,但我只是很好奇。

1 个答案:

答案 0 :(得分: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];
}

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