//.h
//單個(gè)文件的大小,返回多少字節(jié)
+ (long long)fileSizeFor:(NSString*)filePath;
//遍歷文件夾獲得文件夾大小氏仗,返回多少M(fèi)
+ (float ) folderSizeFor:(NSString*)folderPath;
//.m
//單個(gè)文件的大小,返回多少字節(jié)
+ (long long)fileSizeFor:(NSString*)filePath {
NSFileManager* manager = [NSFileManager defaultManager];
if ([manager fileExistsAtPath:filePath]){
return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
}
return 0;
}
//遍歷文件夾獲得文件夾大小,返回多少M(fèi)
+ (float ) folderSizeFor:(NSString*)folderPath {
NSFileManager* manager = [NSFileManager defaultManager];
if (![manager fileExistsAtPath:folderPath]) return 0;
NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
NSString* fileName;
long long folderSize = 0;
while ((fileName = [childFilesEnumerator nextObject]) != nil){
NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
folderSize += [self fileSizeFor:fileAbsolutePath];
}
return folderSize/(1024.0*1024.0);
}
謝謝閱讀莺治!