利用NSFileManager獲取文件(文件夾)列表

 

在開發iPhone程序時,有時候要對文件進行一些操作。而獲取某一個目錄中的所有文件列表,是基本操作之一。通過下面這段代碼,就可以獲取一個目錄內的文件及文件夾列表。

NSFileManager *fileManager = [NSFileManager defaultManager];
//在這裏獲取應用程序Documents文件夾裏的文件及文件夾列表
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir = [documentPaths objectAtIndex:0];
NSError *error = nil;
NSArray *fileList = [[NSArray alloc] init];
//fileList便是包含有該文件夾下所有文件的文件名及文件夾名的數組
fileList = [fileManager contentsOfDirectoryAtPath:documentDir error:&error];

以下這段代碼則可以列出給定一個文件夾裏的所有子文件夾名

NSMutableArray *dirArray = [[NSMutableArray alloc] init];
BOOL isDir = NO;
//在上面那段程序中獲得的fileList中列出文件夾名
for (NSString *file in fileList) {
NSString *path = [documentDir stringByAppendingPathComponent:file];
[fileManager fileExistsAtPath:path isDirectory:(&isDir)];
if (isDir) {
[dirArray addObject:file];
}
isDir = NO;
}
NSLog(@"Every Thing in the dir:%@",fileList);
NSLog(@"All folders:%@",dirArray);

 

 

http://blog.sina.com.cn/s/blog_4adf31ea0100oc0s.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章