- (NSString *)cachesTestPathWithFileName:(NSString *)fileName{
//缓存文件夹路劲
NSString *caches = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
//在caches中添加一个子文件夹(目录)
NSString *cachesTestPath = [caches stringByAppendingPathComponent:@"test"];//创建中间目录
//这是一个单利
NSFileManager *fileManager = [NSFileManager defaultManager];
//判断文件夹是否存在
if (![fileManager fileExistsAtPath:cachesTestPath]) {
//创建文件夹
[fileManager createDirectoryAtPath:cachesTestPath withIntermediateDirectories:YES attributes:nil error:nil];
}
//拼接文件名字
return [caches stringByAppendingPathComponent:fileName];
}
读写文件,text(NSString ),json,plist(NSDictionary,NSArray),png,zip,(NSData)
- (void)viewDidLoad {
[super viewDidLoad];
1.字符串读写文件
//NSString 一般读写成:.txt .json .xml .h .m 等后缀文件
//获取文件沙盒路劲
NSString *strPath = [self cachesTestPathWithFileName:@"str.txt"];
NSLog(@"%@",strPath);
//写文件
BOOL ret = [@"hello world!" writeToFile:strPath atomically:NO encoding:NSUTF8StringEncoding error:nil];
if (ret) {
NSLog(@"完成");
}
//读取文件
NSString *outStr = [NSString stringWithContentsOfFile:strPath encoding:NSUTF8StringEncoding error:nil];
NSLog(@"%@",outStr);
2.NSArray文件读写
//读写成plist
NSString *arrPath = [self cachesTestPathWithFileName:@"arr.plist"];
//写入本地
BOOL arrret = [@[@"12334"] writeToFile:arrPath atomically:NO];
if (arrret) {
NSLog(@"完成");
}
//读取数组
NSArray *outArr = [NSArray arrayWithContentsOfFile:arrPath];
NSLog(@"%@",outArr);
3.字典的读写
//NSDictionary 一般读写成plist文件
NSString *dicPath = [self cachesTestPathWithFileName:@"dic.plist"];
//写入本地
BOOL dicRet = [@{@"abc":@"123456"} writeToFile:dicPath atomically:NO];
if (dicRet) {
NSLog(@"成功");
}
//读取字典
NSDictionary *dicOut = [NSDictionary dictionaryWithContentsOfFile:dicPath];
NSLog(@"%@",dicOut);
//NSData 二进制读写文件
NSString *password = @"123456";
NSData *data = [password dataUsingEncoding:NSUTF8StringEncoding];
//
NSString *dataPath = [self cachesTestPathWithFileName:@"cat.png"];
//二进制写入文件
[data writeToFile:dataPath atomically:NO];
//读取二进制文件
NSData *dataOut = [NSData dataWithContentsOfFile:dataPath];
NSString *strDataOut = [[NSString alloc]initWithData:dataOut encoding:NSUTF8StringEncoding];
NSLog(@"%@",strDataOut);
4.轻量级存储数据
为plist文件,存在沙盒路径下Library下的preferences中
//获取单利对象
NSUserDefaults *UD = [NSUserDefaults standardUserDefaults];
//写入数据
[UD setObject:@[@"魁拔"] forKey:@"kuiba"];
[UD setBool:YES forKey:@"bool"];
[UD setFloat:3.14159256 forKey:@"pi"];
//执行同步
[UD synchronize];
//获取数据
NSLog(@"%f",[UD floatForKey:@"pi"]);
}