获取文件尺寸清除缓存


1. 计算文件尺寸

        // 获取cache文件夹的路径

        NSString *cachePath = directoryPath;       

        // 创建文件管理者

        NSFileManager *manager = [NSFileManager defaultManager];      

        // 判断是否是文件夹

        BOOL isDirectory = NO;

        // 判断当前路径的文件是否存在

        BOOL isExists = [manager fileExistsAtPath:directoryPath isDirectory:&isDirectory];

        // 如果文件不存在或者不是文件夹

        if (!isExists || !isDirectory) {

            @throw [NSException exceptionWithName:@"fileError" reason:@"不是文件夹路径, 或者当前文件夹不存在" userInfo:nil];

        }       

        // 获取文件夹所有子路径数组(缓存文件),可以获取多级目录下文件路径

        NSArray *subpaths = [manager subpathsAtPath:cachePath];

     

// 定义变量保存文件的尺寸

        int totalSize = 0;

// 遍历文件路径

        for (NSString *subPath in subpaths) {

            

            NSString *filePath = [cachePath stringByAppendingPathComponent:subPath];            

            // 如果是隐藏文件夹,就跳过

            if ([filePath containsString:@".DS"]) continue;            

            // 判断是否是文件夹

            BOOL isDirectory = NO;

            // 判断当前路径的文件是否存在

            BOOL isExists = [manager fileExistsAtPath:filePath isDirectory:&isDirectory];

            // 如果文件不存在或者是一个文件夹,就跳过

            if (!isExists || isDirectory) continue;

           

            // 获取文件的属性

            NSDictionary *arrt = [manager attributesOfItemAtPath:filePath error:nil];

            // 计算总尺寸

            totalSize += [arrt fileSize];

        }  

}


2. 删除缓存文件

// 如果指定了一个不存在的文件夹如何处理

    // 创建文件管理者

    NSFileManager *mgr = [NSFileManager defaultManager];

    // 判断是否是文件夹

    BOOL isDirector = NO;

    // 判断当前路径的文件是否存在

    BOOL isExists = [mgr fileExistsAtPath:directoryPath isDirectory:&isDirector];

    if (!isExists || !isDirector) {

        // 抛异常

        @throw [NSException exceptionWithName:@"fillError" reason:@"不是文件夹路径,或者文件夹不存在" userInfo:nil];

    }

    

    // 清除文件夹

    [[NSFileManager defaultManager] removeItemAtPath:directoryPath error:nil];

    // 根据路径创建新的文件夹

    [[NSFileManager defaultManager] createDirectoryAtPath:directoryPath withIntermediateDirectories:YES attributes:nil error:nil];


3. 实现传入一个文件路径就能够获取文件尺寸的字符串

#import <Foundation/Foundation.h>

@interface CQFileManager : NSFileManager

/**
    指定一个文件夹路径,获取当前文件夹路径尺寸
 */
+ (void)getDirectorySize:(NSString *)directoryPath completion:(void(^)(int totalSize))completion;

/**
 *  指定一个文件夹路径,删除这个文件夹
 */
+ (void)removeDirectoryPath:(NSString *)directoryPath;


/**
 *  指定一个文件夹路径,获取当前文件夹尺寸字符串
 */
+ (void)directorySizeString:(NSString *)directoryPath compltion:(void(^)(NSString *directorySize))strCompletion;


@end

#import "CQFileManager.h"

@implementation CQFileManager

// 获取指定路径文件夹尺寸字符串
+ (void)directorySizeString:(NSString *)directoryPath compltion:(void (^)(NSString *directorySize))strCompletion
{

    [CQFileManager getDirectorySize:directoryPath completion:^(int totalSize) {
      
        NSString *str = @"清除缓存";
        // 尺寸
        NSInteger size = totalSize;
        
        if (size > 1000 * 1000) {
            CGFloat fileSize = size / 1000.0 / 1000.0;
            str = [NSString stringWithFormat:@"%@(%0.1fMB)",str, fileSize];
        } else if (size > 1000) {
            CGFloat fileSize = size / 1000.0;
            str = [NSString stringWithFormat:@"%@(%0.1fKB)",str, fileSize];
        } else if (size > 0) {
            str = [NSString stringWithFormat:@"%@(%ldB)",str, size];
        }
        
        str = [str stringByReplacingOccurrencesOfString:@".0" withString:@""];

        if (strCompletion) {
            strCompletion(str);
              }
    }];
}


// 获取指定路径文件夹尺寸
+ (void)getDirectorySize:(NSString *)directoryPath completion:(void (^)(int totalSize))completion
{
    // 在子线程中计算尺寸
    dispatch_async(dispatch_get_global_queue(0, 0), ^{

        // 获取cache文件夹的路径
        NSString *cachePath = directoryPath;
        
        // 创建文件管理者
        NSFileManager *manager = [NSFileManager defaultManager];
        
        // 判断是否是文件夹
        BOOL isDirectory = NO;
        // 判断当前路径的文件是否存在
        BOOL isExists = [manager fileExistsAtPath:directoryPath isDirectory:&isDirectory];
        // 如果文件不存在或者不是文件夹
        if (!isExists || !isDirectory) {
            @throw [NSException exceptionWithName:@"fileError" reason:@"不是文件夹路径, 或者当前文件夹不存在" userInfo:nil];
        }
        // 获取文件夹所有子路径数组(缓存文件),可以获取多级目录下文件路径
        NSArray *subpaths = [manager subpathsAtPath:cachePath];
        
        // 定义变量保存文件的尺寸
        int totalSize = 0;
        // 遍历文件路径
        for (NSString *subPath in subpaths) {
            
            NSString *filePath = [cachePath stringByAppendingPathComponent:subPath];
            // 如果是隐藏文件夹,就跳过
            if ([filePath containsString:@".DS"]) continue;
            
            // 判断是否是文件夹
            BOOL isDirectory = NO;
            // 判断当前路径的文件是否存在
            BOOL isExists = [manager fileExistsAtPath:filePath isDirectory:&isDirectory];
            // 如果文件不存在或者是一个文件夹,就跳过
            if (!isExists || isDirectory) continue;
            
            // 获取文件的属性
            NSDictionary *arrt = [manager attributesOfItemAtPath:filePath error:nil];
            // 计算总尺寸
            totalSize += [arrt fileSize];
        }
        // 回到主线程将文件尺寸转换成字符串并显示
        dispatch_sync(dispatch_get_main_queue(), ^{
            
            if (completion) {
                completion(totalSize);
            }
        });
    });
}

// 删除指定路径文件夹
+ (void)removeDirectoryPath:(NSString *)directoryPath
{
    // 如果指定了一个不存在的文件夹如何处理
    // 创建文件管理者
    NSFileManager *mgr = [NSFileManager defaultManager];
    // 判断是否是文件夹
    BOOL isDirector = NO;
    // 判断当前路径的文件是否存在
    BOOL isExists = [mgr fileExistsAtPath:directoryPath isDirectory:&isDirector];
    if (!isExists || !isDirector) {
        // 抛异常
        @throw [NSException exceptionWithName:@"fillError" reason:@"不是文件夹路径,或者文件夹不存在" userInfo:nil];
    }
    
    // 清除文件夹
    [[NSFileManager defaultManager] removeItemAtPath:directoryPath error:nil];
    // 根据路径创建新的文件夹
    [[NSFileManager defaultManager] createDirectoryAtPath:directoryPath withIntermediateDirectories:YES attributes:nil error:nil];
    
}

@end

#import "CQSettingViewController.h"
#import "CQFileManager.h"

//目标文件路径的宏
#define CachePath [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]

@interface CQSettingViewController ()

@property (nonatomic, strong) NSString *str;

@end

@implementation CQSettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self calculateCacheSize];
    
}

- (void)calculateCacheSize
{
    // 获取当前缓存字符串
    [CQFileManager directorySizeString:CachePath compltion:^(NSString *directorySize) {
        
        _str = directorySize;
        
        [self.tableView reloadData];
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [CQFileManager removeDirectoryPath:CachePath];
    
    // 刷新后没有修改数据是因为没有重新计算缓存大小, 所以刷新后显示的尺寸还是之前保存的str;
//    [self.tableView reloadData];
    
    [self calculateCacheSize];
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值