需要计算文件夹大小,网上看到过一些代码,但是不完全正确,因为没考虑文件夹下面包含文件夹的情况,所以需要递归计算下。
//单个文件的大小
- (long long) fileSizeAtPath:(NSString*) filePath{
NSFileManager* manager = [NSFileManager defaultManager];
if ([manager fileExistsAtPath:filePath]){
return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
}
return 0;
}
//遍历文件夹获得文件夹大小,返回字节
- (long long ) folderSizeAtPath:(NSString*) folderPath{
NSFileManager* manager = [NSFileManager defaultManager];
if (![manager fileExistsAtPath:folderPath])
return 0;
NSString* fileName = [folderPath copy];
long long folderSize = 0;
BOOL isdir;
[manager fileExistsAtPath:fileName isDirectory:&isdir];
if (isdir != YES) {
return [self fileSizeAtPath:fileName];
}
else
{
NSArray * items = [manager contentsOfDirectoryAtPath:fileName error:nil];
for (int i =0; i<items.count; i++) {
BOOL subisdir;
NSString* fileAbsolutePath = [fileName stringByAppendingPathComponent:items[i]];
[manager fileExistsAtPath:fileAbsolutePath isDirectory:&subisdir];
if (subisdir==YES) {
folderSize += [self folderSizeAtPath:fileAbsolutePath]; //文件夹就递归计算
}
else
{
folderSize += [self fileSizeAtPath:fileAbsolutePath];//文件直接计算
}
}
}
return folderSize; //folderSize/(1024*1024)递归时候会运算两次出错,所以返回字节。在外面再计算
}