iOS 计算指定路径下文件尺寸及清理



类的声明


#import <Foundation/Foundation.h>

/**
 
专门处理文件
 */

@interface HWFileManager : NSObject

/**
 
作用 : 指定一个文件夹路径 , 获取文件夹的尺寸
 
参数 (directoryPath): 文件夹路径
 
返回值 : 文件夹尺寸
 */

+ (
void )getSizeOfDirectoryPath:( NSString *)directoryPath completion:( void (^)( int ))completion;

/**
 
作用 : 指定一个文件夹路径 , 清除文件夹
 
参数 (directoryPath): 文件夹路径
 */

+ (
void )removeDirectory:( NSString *)directoryPath;
@end


类的实现

#import "HWFileManager.h"

@implementation HWFileManager
/**
 
作用 : 指定一个文件夹路径 , 获取文件夹的尺寸
 
参数 (directoryPath): 文件夹路径
 
返回值 : 文件夹尺寸
 */



//    就是说传入一个 bool 类型的指针,执行改方法后这个参数的值是 yes 的话就是路径,反之是文件。
/**
    
第一个参数 : 传入文件路劲
    
第二个参数 : 传入一个指针用于记录当前路径下的是否是文件夹
    
返回值 : 是否存在此路径
     fileExistsAtPath:<#(nonnull NSString *)#> isDirectory:<#(nullable BOOL *)#>
     BOOL isDirectory;
     BOOL isExist = [mgr fileExistsAtPath:directoryPath isDirectory:&isDirectory];
 */


// 异步任务 , 不返回数据
+ (
void )getSizeOfDirectoryPath:( NSString *)directoryPath completion:( void (^)( int ))completion {
   
   
dispatch_async ( dispatch_get_global_queue (0, 0), ^{
       
// 子线程执行
       
// 1. 获取文件管理者对象
       
NSFileManager *mgr = [ NSFileManager defaultManager ];
       
// 判断传入文件夹路径是否存在
       
BOOL isDirectory;
       
BOOL isExist = [mgr fileExistsAtPath :directoryPath isDirectory :&isDirectory];
       
       
// 如果不是文件夹或路径不存在 抛出异常
       
if (!isExist || !isDirectory) {
           
@throw [ NSException exceptionWithName : @"FileError" reason : @" 传入路径有问题 " userInfo : nil ];
        }
       
// 定义变量保存尺寸
       
NSInteger totalSize = 0;
       
       
// 2. 获取所有文件 ( 传入文件夹路径 ) // 传入路径获取当前目录下所有子目录文件名称
       
NSArray *subPaths = [mgr subpathsAtPath :directoryPath];
       
       
// 3. 变量所有文件 拼接路径
       
for ( NSString *subPath in subPaths) {
           
// 4. 拼接完整文件名
           
NSString *filePath = [directoryPath stringByAppendingPathComponent :subPath];
           
           
// 判断下是否是隐藏文件
           
if ([subPath hasPrefix : @".DS" ]) continue ;
           
           
// 判断是否是文件夹
           
BOOL isDirectory;
           
// 判断文件路径是否存在 , 并且是否是文件夹
            [mgr
fileExistsAtPath :filePath isDirectory :&isDirectory];
           
if (isDirectory) continue ;
           
           
// 5. 传入文件全路径 , 就能获取文件属性
           
NSDictionary *attr = [mgr attributesOfItemAtPath :filePath error : nil ];
           
           
// 6. 把文件尺寸累加
            totalSize += [attr
fileSize ];
        }
       
       
// 一定要记得回主线程
       
dispatch_sync ( dispatch_get_main_queue (), ^{
           
           
if (completion) {
                completion(totalSize);
            }
        });
    });
   
}

/**
 
作用 : 指定一个文件夹路径 , 清除文件夹
 
参数 (directoryPath): 文件夹路径
 */

+ (
void )removeDirectory:( NSString *)directoryPath {
   
NSFileManager *manager = [ NSFileManager defaultManager ];
   
   
BOOL isDirectory;
//    就是说传入一个 bool 类型的指针,执行改方法后这个参数的值是 yes 的话就是路径,反之是文件。
//  fileExistsAtPath:<#(nonnull NSString *)#> isDirectory:<#(nullable BOOL *)#>
   
BOOL isExist = [manager fileExistsAtPath :directoryPath isDirectory :&isDirectory];
   
   
if (!isExist || !isDirectory) {
       
// 抛出异常 :NSException
       
// name: 异常名字
       // reason:异常原因
        @throw [ NSException exceptionWithName : @"FileError" reason : @" 传入的路径不可以为空 , 或者不是文件夹路径 " userInfo : nil ];
    }
   
// 1. 删除 Cache 文件夹
    [manager
removeItemAtPath :directoryPath error : nil ];
   
// 2. 创建新的 Cache 文件夹
    [manager
createDirectoryAtPath :directoryPath withIntermediateDirectories : YES attributes : nil error : nil ];
}
@end


外界调用

#import <UIKit/UIKit.h>

@interface HWSettingController : UITableViewController

@end


#import "HWSettingController.h"
#import
"HWFileManager.h"
#import
<SVProgressHUD.h>

#define HWCachePath [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]
static
NSString * const ID = @"setting" ;
@interface HWSettingController ()

@property ( nonatomic , assign ) NSInteger totalSize;
@end


@implementation HWSettingController

- (
void )viewDidLoad {
    [
super viewDidLoad ];
   
// 注册 cell
    [
self . tableView registerClass :[ UITableViewCell class ] forCellReuseIdentifier : ID ];
    [
SVProgressHUD showWithStatus : @" 当前正在计算缓存尺寸 ...." ];
   
// 获取路劲
//    NSString *HWCachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
   
// 计算文件尺寸 < 计算完会回调 block 中的代码 >

// 注意:指定文件计算尺寸方法在此调用吐舌头吐舌头

    [ HWFileManager getSizeOfDirectoryPath : HWCachePath completion :^( int totalSize) {
       
// 移除 HUD 显示
        [SVProgressHUDdismiss];
        _totalSize = totalSize;
        // 刷新 tableView 数据
        [
self . tableView reloadData ];
    }];
}

#pragma mark - Table view data source
- ( NSInteger )tableView:( UITableView *)tableView numberOfRowsInSection:( NSInteger )section {
   
return 1;
}

- (
UITableViewCell *)tableView:( UITableView *)tableView cellForRowAtIndexPath:( NSIndexPath *)indexPath {
   
   
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier : ID forIndexPath :indexPath];
   
   
// 设置 Cell
    cell.
textLabel . text = [ self cacheStr ];
   
   
return cell;
}

// 拼接 cell 展示的数据
- (
NSString *)cacheStr
{
   
// 计算 Cache 缓存尺寸
   
// 手机上 1000 点击 1024
   
// 1MB => 1000KB
   
// 1KB => 1000B
   
CGFloat cacheSizeF;
   
NSString *sizeStr = @" 清除缓存 " ;
   
if ( _totalSize > 1000 * 1000) { // MB
        cacheSizeF =
_totalSize / (1000.0 * 1000.0);
        sizeStr = [
NSString stringWithFormat : @"%@(%.1fMB)" ,sizeStr,cacheSizeF];
    }
else if ( _totalSize > 1000) { // KB
        cacheSizeF =
_totalSize / 1000.0;
        sizeStr = [
NSString stringWithFormat : @"%@(%.1fKB)" ,sizeStr,cacheSizeF];
    }
else if ( _totalSize > 0) { // B
        sizeStr = [
NSString stringWithFormat : @"%@(%ldB)" ,sizeStr, _totalSize ];
    }
     // 将.0(小数点后的0)替换为空
    sizeStr = [sizeStr stringByReplacingOccurrencesOfString : @".0" withString : @"" ];
   
return sizeStr;
}

// 注意:清理文件在此调用大笑大笑

// 点击 cell 就会调用
- (
void )tableView:( UITableView *)tableView didSelectRowAtIndexPath:( NSIndexPath *)indexPath
{
   
// 清空缓存
    [
HWFileManager removeDirectory : HWCachePath ];
   
// 将显示尺寸清 0
   
_totalSize = 0;
   
// 刷新表格
    [
self . tableView reloadData ];
}
@end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值