網(wǎng)上有很多方法,但是在文件夾里還有文件夾,嵌套多層的話,大部分都有問(wèn)題,可能需要使用遞歸來(lái)算,事實(shí)上不需要這么麻煩的,直接貼出代碼:
/**
計(jì)算文件/文件夾大小(外部調(diào)用時(shí),請(qǐng)使用子線程)
@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;
//不同點(diǎn)在這里,很多都是for (NSString *fileName in enumerator),但是這樣如果文件夾里還包含文件夾就計(jì)算的不對(duì)了,就需要使用遞歸來(lái)算,比較麻煩
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的時(shí)候,用1024來(lái)?yè)Q算,這個(gè)是錯(cuò)誤的,事實(shí)上蘋(píng)果已經(jīng)為你寫(xiě)好了換算的方法:
[NSByteCountFormatter stringFromByteCount:totalSize countStyle:NSByteCountFormatterCountStyleFile];
這個(gè)方法直接返回一個(gè)字符串(如3.5MB)。