ios文件读写

来源:互联网 发布:图文网站源码 编辑:程序博客网 时间:2024/04/27 17:02

在开发的过程中,经常碰见文件读写的时候,这里我就简单记录一些在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,NSUserDomainMaskYES);

// 传递 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]


原创粉丝点击