iOS 沙盒路径获取,创建文件

沙盒下主要有四个文件夹:document,caches,tmp,library

document 的路径 程序运行时生成的文件,这个文件不要存比较放大的文件,比如音频,视频类,因为这里的东西会被上传

caches 的路径 一般用于文件的下载,存储(不会被上传)

tmp 临时文件.程序结束后应该清空

沙盒文件夹路径获取:

获取沙盒路径:

 NSString *sandBoxPath = NSHomeDirectory();

获取 document :

 NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[];

获取 caches 路径:

 NSString *cacherPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[];

获取 tmp 路径:

 NSString *tmpPath = NSTemporaryDirectory();

在沙盒下创建文件:

1.获取路径

2.拼接文件名(包括后缀)

3.将内容写到文件

例:写一个 txt 文件:

 //NSString 写入

     NSString *str = @"二*";

     //获取 document 路径
NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[]; //拼接上一个 txt 文件
NSString *filePath = [docPath stringByAppendingPathComponent:@"coco.txt"]; //吧字符串写到 txt 文件
[str writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];

例:写一个 array 文件:

 //NSArray

     NSArray *array = @[@"二*",@"三*",@"翠花",@"叶良岑",@"赵日天",@"王尼玛"];

     NSString *tmpPath1 = NSTemporaryDirectory();

     NSString *tmpFilePath = [tmpPath1 stringByAppendingPathComponent:@"tmp.plist"];

     [array writeToFile:tmpFilePath atomically:YES];

例:写一个 dictionary 文件:

 NSDictionary *dic = @{@"1号":@"XXXXX",@"2号":@"XXXXX",@"3号":@"XXXXX",@"4号":@"XXXXX",@"5号":@"XXXXX"};

 NSString *dicPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[];
NSString *dicFilePath = [dicPath stringByAppendingPathComponent:@"dic.plist"]; [dic writeToFile:dicFilePath atomically:YES];

例:写一个 image 文件:

 NSString *cacherPath2 = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[];

 NSString *imgFilePath = [cacherPath2 stringByAppendingPathComponent:@"123.png"];
NSData *data = [[NSData alloc]initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"" ofType:@"png"]]; [data writeToFile:imgFilePath atomically:YES];
上一篇:myBatis系列之七:事务管理


下一篇:2-2-2.开发Java应用(Developing a Java App)