实用工具类的积累是任何一个开发人员必不可少的财富。
遍历Documents目录,获得所有pdf电子书的书名,即文件名列表。这种需求很常见,于是乎,不如来捣鼓一个方法:
/**
@brief 获得指定目录下,指定后缀名的文件列表
@param type 文件后缀名
@param dirPath 指定目录
@return 文件名列表
*/
+(NSArray *) getFilenamelistOfType:(NSString *)type fromDirPath:(NSString *)dirPath;
+(NSArray *) getFilenamelistOfType:(NSString *)type fromDirPath:(NSString *)dirPath;
+(NSArray *) getFilenamelistOfType:(NSString *)type fromDirPath:(NSString *)dirPath;
方法的实现:
+(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]);
}
网友评论