您的位置:首页 > 移动开发 > IOS开发

iOS文件操作

2016-06-27 19:43 337 查看

文件路径

NSSearchPathForDirectoriesInDomain



NSSearchPathDirectory directory:



NSSearchPathDomainMask domainMask:



BOOL expandTilde:

当DomainMask为NSUserDomainMask时,

设为YES,显示完整明确路径为:/Users/jolie/Desktop

设为No时,显示为: ~/Desktop

eg:

NSString *path = [NSSearchPathForDirectoriesInDomains(NSApplicationDirectory, NSAllDomainsMask, NO) firstObject];


stringByAppendingPathComponent

NSString *path = [str stringByAppendingPathComponent:@"Jolie/hello.test"];


读取文件

读取文件分为两种,一种是读取本地文件或者缓存文件,另一种是读取工程中的文件,比如plist配置文件等。

读取本地文件

NSArray *array = [NSArray arrayWithContentsOfFile:path];
NSArray *array = [NSArray arrayWithContentsOfURL:[NSURL URLWithString:path]];

NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];

NSData *data = [[NSData alloc] initWithContentsOfFile:path];
NSData *data = [NSData dataWithContentsOfFile: path];

NSString *string = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];


读取工程文件

NSString *path = [[NSBundle mainBundle] pathForResource:@"hello" ofType:@"plist"];

// 读取类似于缓存文件的读取
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];


写数据

新建文件夹

NSString *folderDir = [desktopDirs[0] stringByAppendingPathComponent:@"CocoaCool"];
[fileManager createDirectoryAtPath:folderDir withIntermediateDirectories:YES attributes:nil error:nil];


写数据道文件中

// m1
NSData *data = ....
[data writeToFile:desktopDir atomically:YES];

NSDictionary *dict = ...
[dict writeToFile:desktopDir atomically: YES];
// m2
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager createFileAtPath:desktopDir contents:data attributes:nil];
// m3 加锁了
[NSKeyedArchiver archiveRootObject:data toFile:desktopDir];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: