FileTool.h 文件
#import <Foundation/Foundation.h>
@interface FileTool : NSObject
/*
* 獲取清除緩存用的方法:
* @pragma directoryPath 文件夾路徑 ;
* @return 返回文件夾的大小
*/
+ (NSInteger)getFileSize:(NSString *)directoryPath ;
/*
* 刪除文件夾子路徑:
* @pragma directoryPath 文件夾路徑 ;
* directoryPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject] ;
* @return 返回文件夾的大小
*/
+ (void)removeCache:(NSString *)directoryPath ;
@end
FileTool.m 文件
#import "FileTool.h"
@implementation FileTool
#pragma mark - 獲取緩存大小
+ (NSInteger)getFileSize:(NSString *)directoryPath {
//NSFileManager
//attributesOfItemAtPath:指定文件路徑 , 就能獲取文件屬性:
//把所有的文件尺寸加起來!
//獲取沙盒目錄中的Cache文件夾的位置:
//NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject] ;
//在Cache文件夾下找到想要的文件夾位置:
//NSString *defaultPath = [cachePath stringByAppendingPathComponent:@"default"] ;
//attributesOfItemAtPath:這個(gè)方法只能獲取文件的大小 , 不能獲取文件夾里所有的文件的大小!所以要遍歷求和!
// 獲取文件管理者:
NSFileManager *manager = [NSFileManager defaultManager] ;
//拋異常:
BOOL isDirectory ;
BOOL isExist = [manager fileExistsAtPath:directoryPath isDirectory:&isDirectory] ;
if (!isExist || !isDirectory) {
NSException *exception = [NSException exceptionWithName:@"pathError" reason:@"請(qǐng)檢查你寫入的地址..." userInfo:nil] ;
//拋出異常:
[exception raise] ;
}
// 獲取文件夾下所有的子路徑: 讓文件管理者去遍歷所有的defalutPath下得子路徑 ;
NSArray *subPath = [manager subpathsAtPath:directoryPath] ;
NSInteger totalSize = 0 ;
for (NSString *filePath in subPath) {
//獲取文件的全路徑:
NSString *holeFilePath = [directoryPath stringByAppendingPathComponent:filePath] ;
//文件的全路徑包含:1.所有文件,2.文件夾,3.隱藏文件:
//判斷是否為隱藏文件:
if ([holeFilePath containsString:@".DS"]) continue ;
//判斷是否為文件夾:
BOOL isDirectory ;
//判斷是否文件存在,是否是個(gè)文件夾?!
BOOL isExist = [manager fileExistsAtPath:holeFilePath isDirectory:&isDirectory] ;
//如果文件不存在,或是個(gè)文件夾:
if (!isExist || isDirectory) continue ;
//獲取全路徑文件屬性:
NSDictionary *attrs = [manager attributesOfItemAtPath:holeFilePath error:nil] ;
//defaultPath的大小:
NSInteger fileSize = [attrs fileSize] ;
//每次遍歷每次++ :
totalSize += fileSize ;
}
NSLog(@"%ld" , totalSize) ;
return totalSize ;
}
+ (void)removeCache:(NSString *)directoryPath {
//清空緩存:
NSFileManager *manager = [NSFileManager defaultManager] ;
BOOL isDirectory ;
BOOL isExist = [manager fileExistsAtPath:directoryPath isDirectory:&isDirectory] ;
if (!isExist || !isDirectory) {
NSException *exception = [NSException exceptionWithName:@"pathError" reason:@"請(qǐng)檢查你寫入的地址..." userInfo:nil] ;
//拋出異常:
[exception raise] ;
}
//獲取文件夾下的二級(jí)路徑 , 不包括更深層的路徑:
NSArray *subPath = [manager contentsOfDirectoryAtPath:directoryPath error:nil] ;
NSLog(@"%@" , subPath) ;
for (NSString *filePath in subPath) {
NSString *holeFilePath = [directoryPath stringByAppendingPathComponent:filePath] ;
[manager removeItemAtPath:holeFilePath error:nil] ;
}
}
@end