计算文件夹大小:
这里随便以YYWebImage的一个文件夹为例
// 累计缓存文件的总大小
unsigned long long fileSize = 0;
// 拼接沙盒路径 library/caches/com.ibireme.yykit/images
NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"com.ibireme.yykit/images"];
// 文件管理者
NSFileManager *fileManager = [NSFileManager defaultManager];
// 取出该路径下(library/caches/com.ibireme.yykit/images)的所有子文件/子文件夹路径集合
NSArray <NSString *>*subPaths = [fileManager subpathsAtPath:cachePath];
// 遍历子路径,累加文件大小
for (NSString *subPath in subPaths) {
// 拼接全路径
NSString *fullPath = [cachePath stringByAppendingPathComponent:subPath];
NSError *error = nil;
NSDictionary *attrs = [fileManager attributesOfItemAtPath:fullPath error:&error];
if (error) {
NSLog(@"%@",error);
}
fileSize += attrs.fileSize;
}
// Mac下按照1000换算
NSLog(@"%llu M",fileSize / (1000 * 1000));
注意点:
-
示例中,直接拿到images文件夹是不能直接获取到总大小的,无论Windows下还是MacOS下,都需要遍历子文件和子文件夹,累加文件的大小
-
在获取子文件和子文件夹时需要使用
subpathsAtPath:
方法;
contentsOfDirectoryAtPath:<#(nonnull NSString *)#> error:<#(NSError * _Nullable __autoreleasing * _Nullable)#>
方法只能获取到子文件夹 -
在遍历子文件/文件夹时,除了通过
subpathsAtPath:
方法外,还可以通过文件夹迭代器
的方式获取自路径集合
// 文件夹迭代器\遍历器
NSDirectoryEnumerator <NSString *>*enumerator = [fileManager enumeratorAtPath:cachePath];
for (NSString *subPath in enumerator) {
// 拼接全路径
NSString *fullPath = [cachePath stringByAppendingPathComponent:subPath];
NSError *error = nil;
NSDictionary *attrs = [fileManager attributesOfItemAtPath:fullPath error:&error];
if (error) {
NSLog(@"%@",error);
}
fileSize += attrs.fileSize;
}
- 如果只是希望获取到YYWebImage产生的缓存,完全可以通过
[YYWebImageManager sharedManager].cache.diskCache.totalCost
来获取到,但如果我们需要对自定义的一些路径进行处理,就会需要我们手动来计算一下了
网友评论