NSFileManager遍历所有文件

- (NSMutableArray *)allFilesAtPath:(NSString *)direString
{
NSMutableArray *pathArray = [NSMutableArray array];

NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *tempArray = [fileManager contentsOfDirectoryAtPath:direString error:nil];
for (NSString *fileName in tempArray) {
BOOL flag = YES;
NSString *fullPath = [direString stringByAppendingPathComponent:fileName];
if ([fileManager fileExistsAtPath:fullPath isDirectory:&flag]) {
if (!flag) {
// ignore .DS_Store
if (![[fileName substringToIndex:1] isEqualToString:@"."]) {
[pathArray addObject:fullPath];
}
}
else {
[pathArray addObject:[self allFilesAtPath:fullPath]];
}
}
}

return pathArray;
}

这个方法返回一个数组,数组里面的数据的类型有字符串和数组两种,而这个数组里面的数据类型也只有字符串和数组两种,以此类推。

众所周知,文件夹包含文件和文件夹。遍历文件夹的内容时,如果是文件就将它的路径以字符串保存起来,如果是文件夹就继续遍历里面的内容,以此类推。

文件夹中会存在.DS_Store,它是用来存储这个文件夹的显示属性的。

 

调用如下:

NSString *documentsDire = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSMutableArray *pathArray = [self allFilesAtPath:documentsDire];



posted on 2012-03-19 22:25  tuyozou  阅读(2660)  评论(2编辑  收藏  举报