将字符串 数组 字典写入本地文件,并计算文件的大小,最后删除文件
2015-12-27 15:21
387 查看
#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; //首先封装一个函数,使得这个函数返回的是我们在指定目录下想要的文件夹的路径 //创建了一个Imgs文件夹 NSString *imgsTmpPath = [self creatDirInTmp:@"Imgs"]; NSLog(@"imgsTmpPath = %@",imgsTmpPath); //将字符串写入本地文件 NSString *targetString = @"Hello guys"; BOOL flag = [targetString writeToFile:[imgsTmpPath stringByAppendingPathComponent:@"a.txt"] atomically:YES encoding:NSUTF8StringEncoding error:nil]; if (flag) { NSLog(@"字符串写入成功"); } else { NSLog(@"字符串写入失败"); } //将数组写入本地文件 NSArray *array = @[@"张国荣",@"Beyond",@"张学友",@"陈奕迅",@"信乐团"]; BOOL flag1 = [array writeToFile:[imgsTmpPath stringByAppendingPathComponent:@"arrary.txt"] atomically:YES]; if (flag1) { NSLog(@"数组写入成功"); } else { NSLog(@"数组写入失败"); } //将字典写入本地 NSDictionary *dictionary = @{@"name":@"Rick",@"age":@"25",@"address":@"Gz"}; BOOL flag2 = [dictionary writeToFile:[imgsTmpPath stringByAppendingPathComponent:@"dictionary.txt"] atomically:YES]; if (flag2) { NSLog(@"字典写入本地成功"); } else { NSLog(@"字典写入本地失败"); } //计算文件大小 //获得将要计算的文件夹 NSFileManager *fileManager = [NSFileManager defaultManager]; //获得imgs目录下文件名组成的数组 NSArray *imgsFileArray = [fileManager subpathsAtPath:imgsTmpPath]; NSLog(@"imgsFileArray = %@",imgsFileArray); /*打印结果: imgsFileArray = ( "a.txt", "arrary.txt", "dictionary.txt" */ //遍历数组 CGFloat count = 0; for (NSString *ele in imgsFileArray) { NSData *data = [NSData dataWithContentsOfFile:[imgsTmpPath stringByAppendingPathComponent:ele]]; count += data.length; } count = count/1024/1024;//将字节转化成M. NSLog(@"缓存文件的大小为:%.2fM",count); //删除文件 for (NSString *ele in imgsFileArray) { BOOL isSuccess = [fileManager removeItemAtPath:[imgsTmpPath stringByAppendingPathComponent:ele] error:nil]; if (isSuccess) { NSLog(@"删除成功"); } else { NSLog(@"删除失败"); } } } //这里我们封装一个函数,使得这个函数返回的是我们在tmp目录下想要的文件夹的路径 -(NSString *)creatDirInTmp:(NSString *)dirName { //获取根目录文件 NSString *tmp = NSTemporaryDirectory(); NSString *dirPath = [tmp stringByAppendingPathComponent:dirName]; NSFileManager *fileManager = [NSFileManager defaultManager]; NSError *error; if (![fileManager fileExistsAtPath:dirPath]) { BOOL isSuccess = [fileManager createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:&error]; if (!isSuccess) { dirPath = nil; NSLog(@"error = %@",error.debugDescription); } } return dirPath; }
相关文章推荐
- 第一类Stirling数和第二类Stirling数
- Servlet
- 【码农流水账】一个码农的成长02
- WebService到底是什么?(转)
- LeetCode Spiral Matrix II
- Linux软件安装之RPM
- 自动化管理工具Saltstack之用户管理篇(6)
- Makefile 使用总结
- 排列组合相关算法 python
- WKWebView显示空白页bug
- Oracle GoldenGate for Big Data 12.2.0.1的新特性
- 有n个整数,指定位置m处插入g个值(用指针和函数)
- Linux网络编程入门
- 056_最长公共子序列
- (Frontend Newbie)Web简史
- 使用Maven Profile按需加载开发、测试和产品环境的配置文件
- cpio命令用法
- 对STL的一些小计
- python3 zip()
- PtSetResource() 导致 Memory fault 的原因分析