//获取沙盒家目录
/*
沙盒目录结构:沙盒路径下一般有三个文件夹
Documents:这里的数据会跟iCloud进行数据同步,一般存放用户信息等小数据。存放过大数据,会被苹果审核小组拒绝。
Library:有些游戏资源会在library下创建子文件夹,进行存储。
caches:用来存放缓存,一般应用重新打开,数据不回丢失。据说,当设备容量不足,可能会清除这里的数据。
Preferences:NSUserDefaults操作的本地plist文件,就在这里。
tmp:临时存储数据的文件夹。应用重新打开可能就会被清理数据。
*/
//这种获取路径方式,最后没有“/”结尾。
NSLog(@"homeDir:%@",NSHomeDirectory());
NSLog(@"homeDir:%@",NSHomeDirectoryForUser(NSUserName()));
//2
//直接获取documents文件夹路径
NSLog(@"documents:%@",NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]);
//直接获取library文件夹路径
NSLog(@"library:%@",NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)[0]);
//直接获取caches文件夹路径
NSLog(@"caches:%@",NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0]);
//沙盒路径实例方法
-(NSString *)cachesPathWith:(NSString *)fileName{
//获取沙盒缓存文件夹路径
NSString * cachesPath=NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
NSLog(@"%@",cachesPath);
//拼接出一个缓存目录下的子目录
NSString * testPath=[cachesPath stringByAppendingPathComponent:@"test"];
NSLog(@"%@",testPath);
//判断目录是否在磁盘真实存在,不存在,需要创建,否则会写文件失败;
NSFileManager * FM=[NSFileManager defaultManager];
if (![FM fileExistsAtPath:testPath isDirectory:NULL]) {
//创建路径。
[FM createDirectoryAtPath:testPath withIntermediateDirectories:YES attributes:nil error:nil];
}
//拼接进文件名称。
NSString * filePath=[testPath stringByAppendingFormat:@"/%@",fileName];
NSLog(@"%@",filePath);
return filePath;
}
字符串读写
//获取需要写入的沙盒文件路径
NSString * filePath=[selfcachesPathWith:@"k.txt"];
//字符串写文件
NSError * error=nil;
BOOL res=[@"tian cangcang,ye mangmang"writeToFile:filePath atomically:YESencoding:NSUTF8StringEncodingerror:&error];
if (res) {
NSLog(@"字符串写入成功");
}else{
NSLog(@"写入失败%@",error);
}
//读取数据;
NSString * txtStr=[NSStringstringWithContentsOfFile:filePathencoding:NSUTF8StringEncodingerror:nil];
NSLog(@"txt:%@",txtStr);
字典读写
//获取缓存路径
NSString * dicPath=[selfcachesPathWith:@"dic.plist"];
//把字典对象写入plist文件
BOOL res=[@{@"2":@"two",@"3":@"three"}writeToFile:dicPath atomically:YES];
if (res) {
NSLog(@"写入成功");
}else{
NSLog(@"写入失败");
}
//读取plist文件
NSDictionary * theDic=[NSDictionarydictionaryWithContentsOfFile:dicPath];
NSLog(@"%@",theDic);
数组读写
//获取沙盒文件路径。NSArray对象使用plist文件进行读写操作
NSString * arrayPath=[selfcachesPathWith:@"array.plist"];
//写文件
[@[@"ABC",@[@"DEF"]]writeToFile:arrayPath atomically:YES];
//读文件:区分plist文件用Array还是Dictionary接收,看最外层。
NSArray * outArr=[NSArrayarrayWithContentsOfFile:arrayPath];
NSLog(@"%@",outArr);
数据流读写
//获取图片路径,指向程序包
NSString * imgPath=[[NSBundlemainBundle]pathForResource:@"wc"ofType:@"png"];
NSLog(@"->%@",imgPath);
//读成data数据
NSData * imgData=[NSDatadataWithContentsOfFile:imgPath];
//获取要写入的沙盒路径
NSString * imgSandboxPath=[selfcachesPathWith:@"tolet.png"];
//数据写入本地文件
[imgData writeToFile:imgSandboxPathatomically:YES];
//读取二进制
NSData * imgOutData=[NSDatadataWithContentsOfFile:imgSandboxPath];
NSLog(@"%@",imgOutData);