iOS文件操作,删除指定后缀文件

来源:互联网 发布:淘宝游戏专营店转让 编辑:程序博客网 时间:2024/05/17 08:29

iOS开发获取path路径下文件夹大小

+ (NSString *)getCacheSizeWithFilePath:(NSString *)path{    // 获取“path”文件夹下的所有文件    NSArray *subPathArr = [[NSFileManager defaultManager] subpathsAtPath:path];    NSString *filePath  = nil;    NSInteger totleSize = 0;    for (NSString *subPath in subPathArr){        // 1. 拼接每一个文件的全路径        filePath =[path stringByAppendingPathComponent:subPath];        // 2. 是否是文件夹,默认不是        BOOL isDirectory = NO;        // 3. 判断文件是否存在        BOOL isExist = [[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&isDirectory];        // 4. 以上判断目的是忽略不需要计算的文件        if (!isExist || isDirectory || [filePath containsString:@".DS"]){            // 过滤: 1. 文件夹不存在  2. 过滤文件夹  3. 隐藏文件            continue;        }        // 5. 指定路径,获取这个路径的属性        NSDictionary *dict = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];        /**         attributesOfItemAtPath: 文件夹路径         该方法只能获取文件的属性, 无法获取文件夹属性, 所以也是需要遍历文件夹的每一个文件的原因         */        // 6. 获取每一个文件的大小        NSInteger size = [dict[@"NSFileSize"] integerValue];        // 7. 计算总大小        totleSize += size;    }    //8. 将文件夹大小转换为 M/KB/B    NSString *totleStr = nil;    if (totleSize > 1000 * 1000){        totleStr = [NSString stringWithFormat:@"%.2fM",totleSize / 1000.00f /1000.00f];    }else if (totleSize > 1000){        totleStr = [NSString stringWithFormat:@"%.2fKB",totleSize / 1000.00f ];    }else{        totleStr = [NSString stringWithFormat:@"%.2fB",totleSize / 1.00f];    }    return totleStr;}

iOS开发删除指定后缀名的文件

+ (BOOL)clearCacheWithExtensionPath:(NSString *)extension {    NSString *cacheFilePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library"];    // 创建文件管理对象    NSFileManager *fileManager = [NSFileManager defaultManager];    // 获取当前缓存路径下的所有子路径    NSArray *subChildPath = [fileManager subpathsOfDirectoryAtPath:cacheFilePath error:nil];    NSError *error = nil;    // 遍历所有子文件夹    for (NSString *subPath in subChildPath) {        // 拼接完整路径        NSString *path = [cacheFilePath stringByAppendingFormat:@"/%@", subPath];        NSString *extPth = [path pathExtension];        if ([extPth isEqualToString:extension]) {            [fileManager removeItemAtPath:path error:&error];            if (error) {                NSLog(@"删除录音文件失败");            }        }    }    return YES;}
0 0