oc 根据文件路径获取文件大小

第一种封装:

-(NSInteger)getSizeOfFilePath:(NSString *)filePath{
/** 定义记录大小 */
NSInteger totalSize = ;
/** 创建一个文件管理对象 */
NSFileManager * manager = [NSFileManager defaultManager];
/**获取文件下的所有路径包括子路径 */
NSArray * subPaths = [manager subpathsAtPath:filePath];
/** 遍历获取文件名称 */
for (NSString * fileName in subPaths) {
/** 拼接获取完整路径 */
NSString * subPath = [filePath stringByAppendingPathComponent:fileName];
/** 判断是否是隐藏文件 */
if ([fileName hasPrefix:@".DS"]) {
continue;
}
/** 判断是否是文件夹 */
BOOL isDirectory;
[manager fileExistsAtPath:subPath isDirectory:&isDirectory];
if (isDirectory) {
continue;
}
/** 获取文件属性 */
NSDictionary *dict = [manager attributesOfItemAtPath:subPath error:nil];
/** 累加 */
totalSize += [dict fileSize]; }
/** 返回 */
return totalSize;
}

第二种  block:

/** 根据文件路径删除文件 */
+(void)removeDirectoryPath:(NSString *)directoryPath{ /** 创建文件管理者 */
NSFileManager * manager = [NSFileManager defaultManager];
/** 判断文件路径是否存在 */
BOOL isDirectory;
BOOL isExist = [manager fileExistsAtPath:directoryPath isDirectory:&isDirectory];
if (!isDirectory||!isExist) {
/** 提示错误信息 */
@throw [NSException exceptionWithName:NSStringFromClass(self) reason:@"文件路径错误!" userInfo:nil];
}
/** 删除文件 */
[manager removeItemAtPath:directoryPath error:nil];
/** 创建文件 */
[manager createDirectoryAtPath:directoryPath withIntermediateDirectories:YES attributes:nil error:nil];
}
/** 根据文件路径获取文件大小 */
+(void)getSizeOfFilePath:(NSString *)filePath completion:(void (^)(NSInteger totalSize))completion{ /** 创建文件管理者 */
NSFileManager * manager = [NSFileManager defaultManager];
/** 判断文件路径是否存在 */
BOOL isDirectory;
BOOL isExist = [manager fileExistsAtPath:filePath isDirectory:&isDirectory];
if (!isDirectory||!isExist) {
/** 提示错误信息 */
@throw [NSException exceptionWithName:NSStringFromClass(self) reason:@"文件路径错误!" userInfo:nil];
}
/** 开启子线程因以下是耗时操作 */
dispatch_async(dispatch_get_global_queue(, ), ^{
/** 定义记录文件大小 */
NSInteger totalSize = ; /** 获取文件 */
NSArray * subPaths = [manager subpathsAtPath:filePath];
/** 遍历文件 */
for (NSString * fileName in subPaths) {
/** 拼接完整路径 */
NSString * subPath = [filePath stringByAppendingPathComponent:fileName];
/** 判断是否是隐藏.DS_Store */
if ([subPath hasPrefix:@".DS"]) {
continue;
}
/** 判断是否是文件夹 */
BOOL isDirectory;
[manager fileExistsAtPath:subPath isDirectory:&isDirectory];
if (isDirectory) {
continue;
}
/** 获取文件属性 */
NSDictionary * dic = [manager attributesOfItemAtPath:subPath error:nil];
totalSize += [dic fileSize];
}
/** 回到主线程 */
dispatch_sync(dispatch_get_main_queue(), ^{
/** block不为空 */
if (completion) {
completion(totalSize);
}
});
}); }
上一篇:js实用功能


下一篇:数据库 MYSQL操作(一)