计算文件夹大小

2017-03-13  本文已影响64人  ShenYj
计算文件夹大小:

这里随便以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));
注意点:
// 文件夹迭代器\遍历器
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;
}
上一篇 下一篇

猜你喜欢

热点阅读