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;}
|
新聞熱點
疑難解答