你的位置:首页 > 操作系统

[操作系统]iOS 沙盒路径获取,创建文件


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

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

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

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

沙盒文件夹路径获取:

获取沙盒路径:

1 NSString *sandBoxPath = NSHomeDirectory();

 

获取 document :

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

获取 caches 路径:

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

 

获取 tmp 路径:

1 NSString *tmpPath = NSTemporaryDirectory();

 

在沙盒下创建文件:

1.获取路径

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

3.将内容写到文件

例:写一个 txt 文件:

 1 //NSString 写入 2    3   NSString *str = @"二傻子"; 4    5   //获取 document 路径 6   NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; 7    8   //拼接上一个 txt 文件 9   NSString *filePath = [docPath stringByAppendingPathComponent:@"coco.txt"];10   11   //吧字符串写到 txt 文件12   [str writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];

例:写一个 array 文件:

 

1 //NSArray2   3   NSArray *array = @[@"二傻子",@"三傻子",@"翠花",@"叶良岑",@"赵日天",@"王尼玛"];4   5   NSString *tmpPath1 = NSTemporaryDirectory();6   7   NSString *tmpFilePath = [tmpPath1 stringByAppendingPathComponent:@"tmp.plist"];8   9   [array writeToFile:tmpFilePath atomically:YES];

 

 

例:写一个 dictionary 文件:

 

1 NSDictionary *dic = @{@"1号":@"XXXXX",@"2号":@"XXXXX",@"3号":@"XXXXX",@"4号":@"XXXXX",@"5号":@"XXXXX"};2   3 NSString *dicPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];4 NSString *dicFilePath = [dicPath stringByAppendingPathComponent:@"dic.plist"];5   6 [dic writeToFile:dicFilePath atomically:YES];

 

 

 

例:写一个 image 文件:

 

1 NSString *cacherPath2 = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];2   3 NSString *imgFilePath = [cacherPath2 stringByAppendingPathComponent:@"123.png"];4 5 NSData *data = [[NSData alloc]initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"1" ofType:@"png"]];6   7 [data writeToFile:imgFilePath atomically:YES];