#import "ZYFileManager.h"
@implementation ZYFileManager
//清空文件夾
+ (void)removeDirectoryPath:(NSString *)directoryPath
{
NSFileManager *mgr = [NSFileManager defaultManager];
BOOL isDirectory;
BOOL isExist = [mgr fileExistsAtPath:directoryPath isDirectory:&isDirectory];
if (!isExist || !isDirectory) {
// 報錯:拋異常
NSException *excp = [NSException exceptionWithName:@"filePathError" reason:@"傳錯,必須傳文件夾路徑" userInfo:nil];
[excp raise];
}
NSArray *subpaths = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:directoryPath error:nil];
for (NSString *subPath in subpaths) {
NSString *filePath = [directoryPath stringByAppendingPathComponent:subPath];
[[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
}
}
// 獲取文件夾尺寸
+ (NSInteger)getDirectorySize:(NSString *)directoryPath
{
// 獲取文件管理者
NSFileManager *mgr = [NSFileManager defaultManager];
BOOL isDirectory;
BOOL isExist = [mgr fileExistsAtPath:directoryPath isDirectory:&isDirectory];
if (!isExist || !isDirectory) {
// 報錯:拋異常
NSException *excp = [NSException exceptionWithName:@"filePathError" reason:@"笨蛋,傳錯,必須傳文件夾路徑" userInfo:nil];
[excp raise];
}
/*
獲取這個文件夾中所有文件路徑,然后累加 = 文件夾的尺寸
*/
// 獲取文件夾下所有的文件
NSArray *subpaths = [mgr subpathsAtPath:directoryPath];
NSInteger totalSize = 0;
for (NSString *subpath in subpaths) {
// 拼接文件全路徑
NSString *filePath = [directoryPath stringByAppendingPathComponent:subpath];
// 排除文件夾
BOOL isDirectory;
BOOL isExist = [mgr fileExistsAtPath:filePath isDirectory:&isDirectory];
if (!isExist || isDirectory) continue;
// 隱藏文件
if ([filePath containsString:@".DS"]) continue;
// 指定路徑獲取這個路徑的屬性
// attributesOfItemAtPath:只能獲取文件屬性
NSDictionary *attr = [mgr attributesOfItemAtPath:filePath error:nil];
NSInteger size = [attr fileSize];
totalSize += size;
}
return totalSize;
}
@end
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者