iOS 常用文件操作方法
程序员文章站
2022-07-03 12:47:11
...
NSString+FileMananger.m
@implementation NSString (FileManager)
+ (NSString *)logsDirectory {
NSString *library = [NSHomeDirectory() stringByAppendingPathComponent:@"Library"];
NSString *filePath = [NSString stringWithFormat:@"Caches/Logs"];
NSString *folder = [library stringByAppendingPathComponent:filePath];
return folder;
}
- (NSString *)calcSize:(NSUInteger)size {
NSString *sizeStr = nil;
// 拿到图片缓存, 将字节转为兆
float cacheSize = size / 1024;
sizeStr = [NSString stringWithFormat:@"%d KB", (int)cacheSize];
if (((int)cacheSize / 1024)) {
cacheSize /= 1024;
sizeStr = [NSString stringWithFormat:@"%.1f M", cacheSize];
} else if (!cacheSize) {
sizeStr = @"没有缓存";
}
return sizeStr;
}
- (NSUInteger)sizeOfFile
{
// 创建一个文件管理者
NSFileManager *mgr = [NSFileManager defaultManager];
NSUInteger fileSize = 0;
BOOL isDir = NO;
if (![mgr fileExistsAtPath:self isDirectory:&isDir]) return 0; //如果文件不存在直接退出
if (isDir) { // 如果是文件夹
// 取出所有子文件
NSArray *subpaths = [mgr subpathsAtPath:self];
// 遍历所有子文件
for (NSString *subpath in subpaths) {
// 拼接拿到文件的全路径
NSString *fullSubPath = [self stringByAppendingPathComponent:subpath];
// 判断是否是文件夹
BOOL isDirectory = NO;
if ([mgr fileExistsAtPath:fullSubPath isDirectory:&isDirectory]) { // 这个文件夹/文件存在
if (isDirectory == NO) { // 是文件
fileSize += [[mgr attributesOfItemAtPath:fullSubPath error:nil][NSFileSize] integerValue];
}
}
}
} else { // 如果是文件
fileSize = [[mgr attributesOfItemAtPath:self error:nil][NSFileSize] integerValue];
}
return fileSize;
}
@end