如何检查文件目录中的文件和从NSBundle复制
问题描述:
我想创建一个应用程序,从文件目录读取文件,但首先我想检查文件目录如果不存在文件自我复制此文件(Db.sqlite)从NSBundle主要文件目录并阅读它。如何检查文件目录中的文件和从NSBundle复制
我可以从文件目录读取数据或检查文件目录,但我不知道如何将文件从NSBundle复制到文件目录。
请指导一下。
答
尝试
- (void)copyDatabaseIfNeeded
{
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
success = [fileManager fileExistsAtPath:[self getDBPath]];
if(success)
{
return;// If exists, then do nothing.
}
//Get DB from bundle & copy it to the doc dirctory.
NSString *databasePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"DB.sqlite"];
[fileManager copyItemAtPath:databasePath toPath:[self getDBPath] error:nil];
}
//Check DB in doc directory.
- (NSString *)getDBPath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:@"DB.sqlite"];
}
它会复制你的数据库中的文档目录,然后你可以从文档目录中使用它。