项目中有个文件管理系统,在做本地文件管理操作的时候,遇到了遍历本地文件的问题
遍历到的文件有些不需要显示,而且需要得到文件的相关属性,在此总结下。
//查找需要遍历文件夹的目录
NSString *kDocumentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
NSFileManager *fm = [NSFileManager defaultManager];
[fm createDirectoryAtPath: [kDocumentsPath stringByAppendingPathComponent:@"localFile"] withIntermediateDirectories:YES attributes:nil error:nil];
NSString *dir = [NSString stringWithFormat:@"%@/localFile",kDocumentsPath];
NSDirectoryEnumerator *dirEnumerater = [fm enumeratorAtPath:dir];
NSString *filePath = nil;
//开始遍历文件
while (nil != (filePath = [dirEnumerater nextObject])) {
NSString *msgdir = [NSString stringWithFormat:@"%@/localFile/%@",kDocumentsPath,filePath];
BOOL isDir;
//比对文件类型,删除不相关类型的文件
if ([fm fileExistsAtPath:msgdir isDirectory:&isDir]) {
if (!isDir) {
if ([[filePath lastPathComponent] isEqualToString:@".DS_Store"]) {
continue;
}
if ([[filePath lastPathComponent] isEqualToString:@"index.htm"]) {
continue;
}
if ([[filePath lastPathComponent] isEqualToString:@"index.html"]) {
continue;
} NSString *fileNameStr = [filePath lastPathComponent];
NSString *filePath = msgdir;
//文件修改时间
NSDictionary *attributes = [fm attributesOfItemAtPath:msgdir error:nil];
NSDate *theModifiDate;
if ((theModifiDate = [attributes objectForKey:NSFileModificationDate])) {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy.MM.dd HH:mm"];
NSString *dateStr = [formatter stringFromDate:theModifiDate];
NSFileManager* manager = [NSFileManager defaultManager];
long long fileSize;
if ([manager fileExistsAtPath:filePath]){
fileSize = [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
}
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:fileNameStr,@"name",filePath,@"path",dateStr,@"time",@(fileSize),@"size", nil];
[localFileArr addObject:dic];
// NSLog(@"\n-----文件名%@\n_______文件路径%@\n======修改时间%@\n-=-=-=-大小 %lld",fileNameStr,filePath,dateStr,fileSize); }
}
}
}