天天看点

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);                                                                                        }