计算下载文件或者数据的大小并写入本地文件同时清除缓存
首先,我是找的网上一个图片。。。网址是
http://e.hiphotos.baidu.com/image/h%3D360/sign=89d0d32471f08202329297397bfafb8a/63d9f2d3572c11df8d778824612762d0f703c216.jpg
用这张图片作为我们今天下载计算的主角。。。。。
代码如下:
首先我们要下载数据。。。。。代码如下:
NSData*data=[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://e.hiphotos.baidu.com/image/h%3D360/sign=89d0d32471f08202329297397bfafb8a/63d9f2d3572c11df8d778824612762d0f703c216.jpg"]];
在次,建议APP开发者将数据以二进制流的形式保存。
第二部:
我们要创建文件的路径。。。。代码:
NSString*path=[NSString stringWithFormat:@"%@/Documents/My.txt",NSHomeDirectory()];
第三部:
我们要创建数据缓存基地。。。。代码如下:
//创建数据缓冲
NSMutableData *writer = [[NSMutableData alloc] init];
//将字符串添加到缓冲中
[writer appendData:data];
第四部: 我们将数据写入文件。。。。。代码如下:
//将缓冲的数据写入到文件中
[writer writeToFile:path atomically:YES];
第五部:
今天的重点计算文件的大小。。。。代码如下并以KB输出。。。。。。
NSFileManager* manager = [NSFileManager defaultManager];
if ([manager fileExistsAtPath:path]){
unsigned long long jk= [[manager attributesOfItemAtPath:path error:nil] fileSize];
NSLog(@"___________%lluKB",jk/1024);
}
下面是效果图展示:
下面的清除缓存。。。。。。。。代码如下:
[manager removeItemAtPath:path error:nil];
效果是:
完整代码如下
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self NextMake];
}
-(void)NextMake
{
NSData*data=[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://e.hiphotos.baidu.com/image/h%3D360/sign=89d0d32471f08202329297397bfafb8a/63d9f2d3572c11df8d778824612762d0f703c216.jpg"]];
// NSFileManager*filemanager=[NSFileManager defaultManager];
NSString*path=[NSString stringWithFormat:@"%@/Documents/My.txt",NSHomeDirectory()];
//创建数据缓冲
NSMutableData *writer = [[NSMutableData alloc] init];
//将字符串添加到缓冲中
[writer appendData:data];
//将缓冲的数据写入到文件中
[writer writeToFile:path atomically:YES];
NSLog(@"%@",path);
NSFileManager* manager = [NSFileManager defaultManager];
if ([manager fileExistsAtPath:path]){
unsigned long long jk= [[manager attributesOfItemAtPath:path error:nil] fileSize];
NSLog(@"___________%lluKB",jk/1024);
}
// BOOL sccuess=[filemanager createFileAtPath:path contents:nil attributes: nil];
// if (sccuess) {
// NSFileManager* manager = [NSFileManager defaultManager];
// if ([manager fileExistsAtPath:path]){
// int jk= (int) [[manager attributesOfItemAtPath:path error:nil] fileSize];
//
// NSLog(@"___________%d",jk);
//
// }else{
//
//
//
// }
// }
//
//
//
//
//清除缓存
[manager removeItemAtPath:path error:nil];
UIImageView*image=[[UIImageView alloc]initWithFrame:self.view.frame];
image.image=[UIImage imageWithData:data];
[self.view addSubview:image];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end