- 目标是遍历Documents目录,获得所有pdf电子书的书名,即文件名列表。
1、 .h文件
/**
* @brief 获得指定目录下,指定后缀名的文件列表
*
* @param type 文件后缀名
* @param dirPath 指定目录
*
* @return 文件名列表
*/
+ (NSArray *) getFilenamelistOfType:(NSString *)type fromDirPath:(NSString *)dirPath;
2、 .m文件(方法的实现:)
+ (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;
}
3、验证一下:
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]);
}
4、结果