项目中有个文件管理系统,在做本地文件管理操作的时候,遇到了遍历本地文件的问题
遍历到的文件有些不需要显示,而且需要得到文件的相关属性,在此总结下。
1 //查找需要遍历文件夹的目录 2 NSString *kDocumentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject; 3 NSFileManager *fm = [NSFileManager defaultManager]; 4 [fm createDirectoryAtPath: [kDocumentsPath stringByAppendingPathComponent:@"localFile"] withIntermediateDirectories:YES attributes:nil error:nil]; 5 NSString *dir = [NSString stringWithFormat:@"%@/localFile",kDocumentsPath]; 6 NSDirectoryEnumerator *dirEnumerater = [fm enumeratorAtPath:dir]; 7 NSString *filePath = nil; 8 //开始遍历文件 9 while (nil != (filePath = [dirEnumerater nextObject])) { 10 NSString *msgdir = [NSString stringWithFormat:@"%@/localFile/%@",kDocumentsPath,filePath]; 11 BOOL isDir; 12 //比对文件类型,删除不相关类型的文件 13 if ([fm fileExistsAtPath:msgdir isDirectory:&isDir]) { 14 if (!isDir) { 15 if ([[filePath lastPathComponent] isEqualToString:@".DS_Store"]) { 16 continue; 17 } 18 if ([[filePath lastPathComponent] isEqualToString:@"index.htm"]) { 19 continue; 20 } 21 if ([[filePath lastPathComponent] isEqualToString:@"index.html"]) { 22 continue; 23 } 24 25 NSString *fileNameStr = [filePath lastPathComponent]; 26 NSString *filePath = msgdir; 27 //文件修改时间 28 NSDictionary *attributes = [fm attributesOfItemAtPath:msgdir error:nil]; 29 NSDate *theModifiDate; 30 if ((theModifiDate = [attributes objectForKey:NSFileModificationDate])) { 31 NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 32 [formatter setDateFormat:@"yyyy.MM.dd HH:mm"]; 33 NSString *dateStr = [formatter stringFromDate:theModifiDate]; 34 NSFileManager* manager = [NSFileManager defaultManager]; 35 long long fileSize; 36 if ([manager fileExistsAtPath:filePath]){ 37 fileSize = [[manager attributesOfItemAtPath:filePath error:nil] fileSize]; 38 } 39 NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:fileNameStr,@"name",filePath,@"path",dateStr,@"time",@(fileSize),@"size", nil]; 40 [localFileArr addObject:dic]; 41 // NSLog(@" -----文件名%@ _______文件路径%@ ======修改时间%@ -=-=-=-大小 %lld",fileNameStr,filePath,dateStr,fileSize); 42 43 } 44 } 45 } 46 }