2013-05-16 30 views
0

我想創建一個應用程序,從文件目錄讀取文件,但首先我想檢查文件目錄如果不存在文件自我複製此文件(Db.sqlite)從NSBundle主要文件目錄並閱讀它。如何檢查文件目錄中的文件和從NSBundle複製

我可以從文件目錄讀取數據或檢查文件目錄,但我不知道如何將文件從NSBundle複製到文件目錄。

請指導一下。

回答

4

嘗試

- (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"]; 
    } 

它會複製你的數據庫中的文檔目錄,然後你可以從文檔目錄中使用它。

相關問題