ios文件讀寫

在開發的過程中,經常碰見文件讀寫的時候,這裏我就簡單記錄一些在ios開發裏面的文件讀寫api,爲了以後用着方便。
ios開發裏面,文件的目錄是固定的,可以用 NSHomeDirectory()方法讀取項目文件的目錄,
NSString* path = NSHomeDirectory();
這樣得到的應用程序的主目錄,基本是不會變的,完整的模擬器路徑可能是這樣的:/Users/cadamson/Libary/Application Support/iPhone Simulator/User/Applications/5c73EBC6-...-...-...-,最後一部分就是一個隨機生成的應用程序ID,這個id每次構建應用時都會重新聲成。當然,由於iphone的安全模型不允許訪問到任何此目錄之上的目錄層次,所以這個目錄的名稱以及它上面目錄的名稱其實根本無關緊要

    在這個目錄下面,有四個目錄需要了解:
-Documents -- 這是用來儲存用戶文件的首選目錄。
-Application - Name --這個目錄是你的應用程序包,包括了nib文件,本地化資源,可以執行代碼以及別的資源。
-Library --  這個目錄作爲Preference目錄的父目錄而單獨存在
-tmp -- 

訪問文件:
NSFileManager 是用來訪問文件系統的主要類:

    NSFileManager *fileManager = [NSFileManager defaultManager];


<>查找文件:

NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

// 傳遞 0 代表是找在Documents 目錄下的文件。

 NSString *documentDirectory = [paths objectAtIndex:0];

// DBNAME 是要查找的文件名字,文件全名 

NSString *filePath = [documentDirectory stringByAppendingPathComponent:DBNAME];

// 用這個方法來判斷當前的文件是否存在,如果不存在,就創建一個文件

if ( ![fileManager fileExistsAtPath:path]) {

        [fileManager createFileAtPath:path contents:nil attributes:nil];  

    }


<3>讀取文件數據:

   //分別用NSData 和NSString,NSMutableDictionary來讀取文件內容

NSData* fileData = [NSData dataWithContentsOfFile:DBNAME];

 NSString* myString = [NSString stringWithContentsOfFile:DBNAME usedEncoding:NULL error:NULL];

 NSMutableDictionary* dict = [[NSMutableDictionary alloc]initWithContentsOfFile:fileName];

<4>把數據寫入文件

 NSString* fileName = [[filePath objectAtIndex:0]stringByAppendingPathComponent:DBNAME];

[fileData writeToFile:fileName atomically:YES]



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章