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

本文介绍了一种在iOS开发中获取指定路径下文件夹大小的方法,并提供了一个用于删除指定后缀名文件的实用函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值