網(wǎng)上有很多方法,但是在文件夾里還有文件夾,嵌套多層的話,大部分都有問題,可能需要使用遞歸來算,事實上不需要這么麻煩的,直接貼出代碼:
/**
計算文件/文件夾大小(外部調(diào)用時,請使用子線程)
@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];
}
}
}
有人在轉(zhuǎn)換成MB的時候,用1024來換算,這個是錯誤的,事實上蘋果已經(jīng)為你寫好了換算的方法:
[NSByteCountFormatter stringFromByteCount:totalSize countStyle:NSByteCountFormatterCountStyleFile];
這個方法直接返回一個字符串(如3.5MB)。