我从其他地方获得了这个代码并进行了一些编辑,允许使用enumeratorAtPath
指定的起始路径遍历所有目录。使用此代码,我可以使用isReadableFileAtPath
检索具有读取属性的特定扩展名的文件。我想要的是检索具有读取属性的任何扩展名的所有文件,并根据它们的最后文件夹名称将它们分类到不同的类别。
例如,如果我有一个路径/a/b/c/example.plist,/a/b/c/example.plist将被归类为c。
- (NSString *) retrievePaths
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSMutableString *filePaths = [[NSMutableString alloc] init];
NSDirectoryEnumerator *dirnum = [[NSFileManager defaultManager] enumeratorAtPath:@"/"];
NSString *nextItem = [NSString string];
int i = 0;
while( (nextItem = [dirnum nextObject]))
{
if([[nextItem pathExtension] isEqualToString:@"db"] || [[nextItem pathExtension] isEqualToString:@"sqlitedb"] || [[nextItem pathExtension] isEqualToString:@"sqlite"]) {
if([fileManager isReadableFileAtPath:nextItem])
{
i++;
[filePaths appendFormat:@"%d)",i];
[filePaths appendString:nextItem];
[filePaths appendString:@"\n"];
}
}
}
NSString *format = [NSString stringWithFormat:@"Paths : %@", filePaths];
return format;
}
答案 0 :(得分:1)
从代码中移除以下if条件,您将能够获得具有可读访问权限的所有文件
if([[nextItem pathExtension] isEqualToString:@"db"] || [[nextItem pathExtension] isEqualToString:@"sqlitedb"] || [[nextItem pathExtension] isEqualToString:@"sqlite"])
修改强>
更新的功能试试这个,对你有用..
- (NSString *) retrievePaths
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSMutableString *filePaths = [[NSMutableString alloc] init];
NSString *path = @"/Assign/your/path/"; // assign your path
NSDirectoryEnumerator *dirnum = [[NSFileManager defaultManager] enumeratorAtPath:path];
NSString *nextItem = [NSString string];
int i = 0;
while( (nextItem = [dirnum nextObject]))
{
NSString *filePath = [path stringByAppendingPathComponent:nextItem];
BOOL isDir = NO;
[[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&isDir];
if(NO == isDir) {
if([fileManager isReadableFileAtPath:filePath])
{
i++;
[filePaths appendFormat:@"%d)",i];
[filePaths appendString:nextItem];
[filePaths appendString:@"\n"];
}
}
}
NSString *format = [NSString stringWithFormat:@"Paths : %@", filePaths];
return format;
}