iOS開發——遍歷目錄,獲取檔名列表
阿新 • • 發佈:2019-01-30
實用工具類的積累是任何一個開發人員必不可少的財富。
今天的任務是遍歷Documents目錄,獲得所有pdf電子書的書名,即檔名列表。這種需求很常見,於是乎,不如來搗鼓一個方法:
[cpp] view plain copy print?- /**
- * @brief 獲得指定目錄下,指定字尾名的檔案列表
- *
- * @param type 檔案字尾名
- * @param dirPath 指定目錄
- *
- * @return 檔名列表
- */
-
+(NSArray *) getFilenamelistOfType:(NSString *)type fromDirPath:(NSString *)dirPath;
方法的實現: [cpp] view plain copy print?
- +(NSArray *)getFilenamelistOfType:(NSString *)type fromDirPath:(NSString *)dirPath
- {
- NSMutableArray *filenamelist = [NSMutableArray arrayWithCapacity:10];
-
NSArray *tmplist = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:dirPath error:nil];
- for (NSString *filename in tmplist) {
- NSString *fullpath = [dirPath stringByAppendingPathComponent:filename];
- if ([self isFileExistAtPath:fullpath]) {
- if ([[filename pathExtension] isEqualToString:type]) {
-
[filenamelist addObject:filename];
- }
- }
- }
- return filenamelist;
- }
- +(BOOL)isFileExistAtPath:(NSString*)fileFullPath {
- BOOL isExist = NO;
- isExist = [[NSFileManager defaultManager] fileExistsAtPath:fileFullPath];
- return isExist;
- }
- NSArray *filename = [WQFileManager getFilenamelistOfType:@"pdf"
- fromDirPath:[WQPathUtilities documentsDirectory]];
- NSInteger count = filename.count;
- NSLog(@"I have %d books in DocumentsDir",count);
- for (int i = 0; i<count; i++) {
- NSLog(@"NO.%d is %@",i+1,[filename objectAtIndex:i]);
- }
OK,完成任務!