您好,欢迎来到爱go旅游网。
搜索
您的当前位置:首页ios文件读写

ios文件读写

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

 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]



因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- igat.cn 版权所有 赣ICP备2024042791号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务