根據(jù)上一篇計算文件夾大小文章進一步擴展,封裝一個自動根據(jù)路徑獲取該文件或文件夾的大小的NSString分類
#import "NSString+JSFileSize.h"
@implementation NSString (JSFileSize)
- (unsigned long long)fileSize {
unsigned long long fileSize = 0;
// 文件管理者
NSFileManager *fileManager = [NSFileManager defaultManager];
// 通過當前路徑獲取文件或文件夾
NSError *error = nil;
NSDictionary *attributes = [fileManager attributesOfItemAtPath:self error:&error];
if (error || !attributes) {
NSLog(@"%@",error);
return 0.0;
}
// 判斷類型 文件 或 文件夾 或者 其他
NSString *fileType = attributes.fileType;
if ([fileType isEqualToString:NSFileTypeDirectory]) {
// 文件夾
NSArray <NSString *>*subPaths = [fileManager subpathsAtPath:self];
// 遍歷子路徑,累加文件大小
for (NSString *subPath in subPaths) {
// 拼接全路徑
NSString *fullPath = [self stringByAppendingPathComponent:subPath];
NSError *error = nil;
NSDictionary *attrs = [fileManager attributesOfItemAtPath:fullPath error:&error];
if (error) {
NSLog(@"%@",error);
}
fileSize += attrs.fileSize;
}
} else if ([fileType isEqualToString:NSFileTypeRegular]) {
// 文件
fileSize = attributes.fileSize;
}
return fileSize;
}
- (void)logFileSize {
unsigned long long fileSize = 0;
// 文件管理者
NSFileManager *fileManager = [NSFileManager defaultManager];
// 是否為文件夾
BOOL isDirectory = NO;
// 路徑是否仔仔
BOOL isExist = [fileManager fileExistsAtPath:self isDirectory:&isDirectory];
if (!isExist) {
return;
}
if (isDirectory) {
// 文件夾
NSArray <NSString *>*subPaths = [fileManager subpathsAtPath:self];
// 遍歷子路徑,累加文件大小
for (NSString *subPath in subPaths) {
// 拼接全路徑
NSString *fullPath = [self stringByAppendingPathComponent:subPath];
NSError *error = nil;
NSDictionary *attrs = [fileManager attributesOfItemAtPath:fullPath error:&error];
if (error) {
NSLog(@"%@",error);
}
fileSize += attrs.fileSize;
}
} else {
// 通過當前路徑獲取文件或文件夾
NSError *error = nil;
NSDictionary *attributes = [fileManager attributesOfItemAtPath:self error:&error];
if (error || !attributes) {
NSLog(@"%@",error);
return ;
}
// 文件
fileSize = attributes.fileSize;
}
NSLog(@"文件/文件夾大小:%llu B",fileSize);
}
@end
封裝了兩個方法
/** 返回文件或文件夾的大小,單位B */
- (unsigned long long)fileSize;
/** 控制臺打印文件或文件夾大小 */
- (void)logFileSize;
兩個方法中fileSize
用于返回具體的值,而logFileSize
只用于控制臺的打印
主要區(qū)別在于判斷是文件還是文件夾的方式不同,計算的過程完全一致
這樣在開發(fā)中,我們只需要拼接好路徑來調用API即可