NSFileManager計算文件/文件夾大小


在一些軟件中,一般都會給用戶展現當前APP的內存,同時用戶可以根據自己的需要來清除緩存的內容。一般而言,文件夾是沒有大小這個屬性的,所以需要遍歷文件夾的內容來計算文件夾的大小,下面用NSFileManger來實現這個功能。

了解到文件/文件夾路徑是一個NSString字符串類型,所以可以給字符串添加分類,如果其是文件/文件夾實現計算其大小的功能。分類命名為fileSize.

 1 - (NSInteger)fileSize{
 2     //文件管理者
 3     NSFileManager *mgr = [NSFileManager defaultManager];
 4     //判斷字符串是否為文件/文件夾
 5     BOOL dir = NO;
 6     BOOL exists = [mgr fileExistsAtPath:self isDirctory:&dir];
 7     //文件/文件夾不存在
 8     if (exists == NO) return 0;
 9     //self是文件夾
10     if (dir){
11          //遍歷文件夾中的所有內容
12          NSArray *subpaths = [mgr subpathsAtPath:self];
13          //計算文件夾大小
14          NSInteger totalByteSize = 0;
15          for (NSString *subpath in subpaths){
16               //拼接全路徑
17                NSString *fullSubPath = [self stringByAppendingPathComponent:subpath];
18             //判斷是否為文件
19             BOOL dir = NO;
20             [mgr fileExistsAtPath:fullSubPath isDirectory:&dir];
21             if (dir == NO){//是文件
22                    NSDictionary *attr = [mgr attributesOffItemAtPath:fullSubPath error:ni];
23                    totalByteSize += [attr[NSFileSize] integerValue];
24              }
25          }
26          return totalByteSize;      
27     } else{//是文件
28           NSDictionary *attr = [mgr attributesOffItemAtPath:self error:ni];
29            return [attr[NSFileSize] integerValue];
30    }   
31 }    

這樣就可以實現文件/文件夾大小的計算

比如計算Caches文件的大小

1 NSString *caches =[[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
2 Integer cachesSize = [caches fileSize];

這樣就得到了caches文件夾的大小。

如果輸入的字符串不是文件/文件夾的時候,得到0。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM