iOS随记-计算文件夹大小

网上有很多方法,但是在文件夹里还有文件夹,嵌套多层的话,大部分都有问题,可能需要使用递归来算,事实上不需要这么麻烦的,直接贴出代码:

/**
 计算文件/文件夹大小(外部调用时,请使用子线程)

 @param filePath 文件/文件夹路径
 @return 返回文件/文件夹大小
 */
+ (long long)getFileSizeForFilePath:(NSString *)filePath {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDir = NO;
    BOOL exists = [fileManager fileExistsAtPath:filePath isDirectory:&isDir];
    if (!exists) {
        return 0;
    }
    if (isDir) {//如果是文件夹
        NSDirectoryEnumerator *enumerator = [fileManager enumeratorAtPath:filePath];
        long long totalSize = 0;
      //不同点在这里,很多都是for (NSString *fileName in enumerator),但是这样如果文件夹里还包含文件夹就计算的不对了,就需要使用递归来算,比较麻烦
        for (NSString *fileName in enumerator.allObjects) {
            //文件路径
            NSString *fullFilePath = [filePath stringByAppendingPathComponent:fileName];
            //判断是否为文件
            BOOL isFullDir = NO;
            [fileManager fileExistsAtPath:fullFilePath isDirectory:&isFullDir];
            if (!isFullDir) {
                NSError *error = nil;
                NSDictionary *dict = [fileManager attributesOfItemAtPath:fullFilePath error:&error];
                if (!error) {
                    totalSize += [dict[NSFileSize] longLongValue];
                }
            }
        }
        return totalSize;
    } else {//是文件
        NSError *error = nil;
        NSDictionary *dict = [fileManager attributesOfItemAtPath:filePath error:&error];
        if (error) {
            Plog(@"文件大小获取失败--%@", error);
            return 0;
        } else {
           return [dict[NSFileSize] longLongValue];
        }
    }
}

有人在转换成MB的时候,用1024来换算,这个是错误的,事实上苹果已经为你写好了换算的方法:

[NSByteCountFormatter stringFromByteCount:totalSize countStyle:NSByteCountFormatterCountStyleFile];

这个方法直接返回一个字符串(如3.5MB)。

你可能感兴趣的:(iOS随记-计算文件夹大小)