天天看點

iOS開發-檔案管理(一)

一、ios中的沙盒機制

ios應用程式隻能對自己建立的檔案系統讀取檔案,這個獨立、封閉、安全的空間,叫做沙盒。它一般存放着程式封包件(可執行檔案)、圖檔、音頻、視訊、plist檔案、sqlite資料庫以及其他檔案。

每個應用程式都有自己的獨立的存儲空間(沙盒)

一般來說應用程式之間是不可以互相通路

模拟器沙盒的位置

/user/username/library/application support/iphone simulator

當我們建立應用程式時,在每個沙盒中含有三個檔案,分别是document、library和temp。

document:一般需要持久的資料都放在此目錄中,可以在當中添加子檔案夾,itunes備份和恢複的時候,會包括此目錄。

library:設定程式的預設設定和其他狀态資訊

temp:建立臨時檔案的目錄,當ios裝置重新開機時,檔案會被自動清除

擷取沙盒目錄

擷取程式的根目錄(home)目錄

nsstring *homepath = nshomedirectory()

擷取document目錄

nsarray  *paths = nssearchpathdordirectoriesindomains(nsdocumentdicrectory,, nsuserdomainmark, yes);                                                                           nsstring *docpath = [paths lastobject];

擷取library目錄

nsarray *paths = nssearchpathfordirectoriseindomains(nslibrarydirectory, nsuserdomainmask, yes);                                                                                   nsstring *docpath = [paths lastobject];   

擷取library中的cache

nsarray *paths = nssearchpathfordirectoriseindomains(nscachesdirectory, nsuserdomainmask, yes);                                                                                   nsstring *docpath = [paths lastobject];

擷取temp路徑

nsstring *temp = nstemporarydirectory( );

二、nsstring類路徑的處理方法

檔案路徑的處理

nsstring *path = @"/uesrs/apple/testfile.txt"

常用方法如下

獲得組成此路徑的各個組成部分,結果:("/","user","apple","testfile.txt")

- (nsarray *)pathcomponents;

提取路徑的最後一個組成部分,結果:testfile.txt

- (nsstring *)lastpathcomponent;

删除路徑的最後一個組成部分,結果:/users/apple

- (nsstring *)stringbydeletinglastpathcpmponent;

将path添加到先郵路徑的末尾,結果:/users/apple/testfile.txt/app.txt

- (nsstring *)stringbyappendingpathconmponent:(nsstring *)str;

去路徑最後部分的擴充名,結果:text

- (nsstring *)pathextension;

删除路徑最後部分的擴充名,結果:/users/apple/testfile

- (nsstring *)stringbydeletingpathextension;

路徑最後部分追加擴充名,結果:/user/apple/testfile.txt.jpg

- (nsstring *)stringbyappendingpathextension:(nsstring *)str;

三、nsdata

nsdata是用來包裝資料的

nsdata存儲的是二進制資料,屏蔽了資料之間的差異,文本、音頻、圖像等資料都可用nsdata來存儲

nsdata的用法

1.nsstring與nsdata互相轉換

nsdata-> nsstring                                                                                     nsstring *astring = [[nsstring alloc] initwithdata:adataencoding:nsutf8stringencoding];

nsstring->nsdata                                                                                      nsstring *astring = @"1234abcd";

nsdata *adata = [astring datausingencoding: nsutf8stringencoding]; 

将data類型的資料,轉成utf8的資料

+(nsstring *)datatoutf8string:(nsdata *)data

{

nsstring *buf = [[nsstring alloc] initwithdata:data encoding:nsutf8stringencoding];

return [buf autorelease];

}

将string轉換為指定編碼 

+(nsstring *)changedatatoencodinstring:(nsdata *)data encodin:(nsstringencoding )encodin{

    nsstring *buf = [[[nsstring alloc] initwithdata:data encoding:encodin] autorelease];

    return buf;

2. nsdata 與 uiimage

nsdata->uiimage

uiimage *aimage = [uiimage imagewithdata: imagedata];

//例:從本地檔案沙盒中取圖檔并轉換為nsdata

nsstring *path = [[nsbundle mainbundle] bundlepath];

nsstring *name = [nsstring stringwithformat:@"ceshi.png"];

nsstring *finalpath = [path stringbyappendingpathcomponent:name];

nsdata *imagedata = [nsdata datawithcontentsoffile: finalpath];

3.nsdata與nsarray  nsdictionary

+(nsstring *)getlocalfilepath:(nsstring *) filename

包括将nsdata寫進documents目錄

從documents目錄讀取資料

在進行網絡資料通信的時候,經常會遇到nsdata類型的資料。在該資料是dictionary結構的情況下,系統沒有提供現成的轉換成nsdictionary的方法,為此可以通過category對nsdictionary進行擴充,以支援從nsdata到nsdictionary的轉換。聲明和實作如下:

+ (nsdictionary *)dictionarywithcontentsofdata:(nsdata *)data {     

    cfpropertylistref list = cfpropertylistcreatefromxmldata(kcfallocatordefault, (cfdataref)data, kcfpropertylistimmutable, null);

    if(list == nil) return nil; 

    if ([(id)list iskindofclass:[nsdictionary class]]) { 

         return [(nsdictionary *)list autorelease]; 

        } 

    else { 

         cfrelease(list); 

         return nil; 

四、檔案管理常用方法

nsfilemanager

建立一個檔案并寫入資料                                                                                    - (bool)createfileatpath:(nsstring *)path contents:(nsdata *)data attributes:(nsdictionary *)attr;

從一個檔案中讀取資料                                                                                       - (nsdata *)contentsatpath:(nsstring *)path;

scrpath路徑上的檔案移動到dstpath路徑上,注意這裡的路徑是檔案路徑而不是目錄          - (bool)moveitematpath:(nsstring *)srcpath topath:(nsstring *)dstpath error:(nserror **) error;

scrpath路徑上的檔案複制到dstpath路徑上                                                            - (bool)copyitematpath:(nsstring *)scrpath topath:(nsstring *)dstpath error:(nserror **) error;

比較兩個檔案的内容是否一樣                                                                               - (bool)contentsequalatpath:(nsstring *)path1 andpath:(nsstring *)path2;

檔案時候存在                                                                                                  - (bool)fileexistsatpath:(nsstring *)path;

移除檔案                                                                                                        - (bool)removeitematpath:(nsstring *)path error:(nserror **) error;

建立檔案管理

nsfilemanager *filemanager = [nsfilemanager defaultmanager];                          nsstring *path = [nshomedirectory( )  stringbyappendingpathcomponent:@"holybible.txt"];                                                                                                    

nsstring *text = @"abcdefg"; 

将字元串轉成nsdata類型                                                                                 nsdata *data = [text datausingencoding: nsutf8stringencoding]; 

寫入檔案                                                                                                       bool success = [filemanager createfileatpath:path contents:data attributes:nil];

建立檔案夾 

nsstring *filepath = [path stringbyappendingpathcomponent:@"holybible.txt"];     nsstring *contect = @"abcdefg";                                                                     bool success = [fm createfileatpath:filepath contents:[content datausingencoding:

nsutf8stringencoding] attributes:nil];

nsfilemanager-讀取内容                                                                                 nsdata *filedata = [filemanager contentsatpath:filepath];                                   nsstring *content = [[nsstring

alloc] initwithdata:filedata datausingencoding: nsutf8stringencoding];

nsdata-讀取内容                                                                                          nsstring *filepath = [path stringbyappendingpathcomponent:@"holybible.txt"];     nsdata *data = [nsdata datawithcontentoffile:filepath];

nsstring-讀取内容                                                                                         nsstring *filepath = [path stringbyappendingpathcomponent:@"holybible.txt"];     nsstring *content = [[nsstring

stringwithcontentsoffile:filepath encoding:nsutf8stringencoding error:nil];

移動、複制檔案                                                                                             

移動檔案(重命名)                                                                                         nsstring *topath = [nshomedirectory( ) stringbyappendingpathcomponent:@"hellogod/new testament.txt"];                                                                              [fm

createdirectoryatpath:[topath stringbydeletinglastpathcomponent] withintermediatedirectories:yes attributes:nil error:nil];                                                   nserror *error;                                                                                            

bool issuccess = [fm moveitematpath:filepath topath:topath error:&error];

複制檔案(重命名)                                                                                         nsstring *copypath = [nshomedirectory( ) stringbyappendingpathcomponent:@"備份/old testament.txt"];                                                                                  [fm

createdirectoryatpath:[topath stringbydeletinglastpathcomponent] withintermediatedirectories:yes attributes:nil error:nil];                                                   bool success = [fm copyitematpath:topath topath:topath error:nil];

删除檔案、擷取檔案大小

判斷檔案是否存在和删除檔案                                                                               if([fm fileexistsatpath])                                                                                     {                                                                                                                   

if ([fm removeitematpath:copypath])                                                                {                                                                                                                   nslog(@"remove success");                                                                            }                                                                                                                  }

擷取檔案大小                                                                                                  nsfilemanager *filemanager = [nsfilemanager defaultmanager];                         獲得檔案的屬性字典                                                                                        

nsdictionary *attrdic = [filemanager attributesofitematpath:sourcepath error:nil];  nsnumber *filesize = [attrdic objectforkey:nsfilesize];   

擷取目錄檔案資訊                                                                                            nsfilemanager *filemanager = [nsfilemanager defaultmanager];                         nsstring *enupath = [nshomedirectoty( )

stringbyappendingpathcomponent:@"test"];                                                                                                           nsdictionaryenumerator *direnum = [filemanager enumeratoratpath:enupath];     nsstring *path = nil;                                                                                     

while ((path = [direnum nextobject]} != nil)                                                        {                                                                                                                  nslog(@"%@",path);                                                                                        }