如何检索特定文件扩展名的文件的文件路径?

问题描述:

我已经解压缩文件,发送到我的文档目录:如何检索特定文件扩展名的文件的文件路径?

[SSZipArchive unzipFileAtPath:path toDestination:destinationPath]; 

在解压文件将有5种不同类型的文件。我只想知道扩展名为'.shp'的文件的路径和文件名。

我已经试过如下:

NSString *filePath = [[NSBundle mainBundle] pathForResource:destinationPath ofType:@"shp"]; 

之后,我想删除该文件夹中的文件的所有内容。

任何想法?提前致谢。

+0

请检查我的答案,让我知道,如果这是你在找什么 – KrishnaCA

首先,获取所有目录文件。

NSString *bundle = [[NSBundle mainBundle] bundlePath]; 
NSFileManager * aMan = [NSFileManager defaultManager]; 
NSArray * allFiles = [aMan contentsOfDirectoryAtPath: bundle]; 

则可以用以下的方法之一来筛选所需的扩展:

NSPredicate *filter = [NSPredicate predicateWithFormat:@"self ENDSWITH '.shp'"]; 
NSArray *filtered = [allFiles filteredArrayUsingPredicate:filter]; 

下一页 - 删除文件,循环过滤。但它对我来说并不好。
所以,我更喜欢这一个:

NSError *error; 
for (NSString * elem in allFiles) { 
    if ([[elem pathExtension] isEqualToString:@"shp"]) 
     [aMan removeItemAtPath:[bundle stringByAppendingPathComponent:elem] error:&error]; 

希望,它有助于

find . -iname "*.shp" 

这里'。'代表在当前和它的子文件夹中搜索。您甚至可以指定目录路径而不是'。',您要在其中搜索。或者,如果您搜索整个根目录,则可以使用“/”。 '-i'表示扩展名不区分大小写。 '-iname'用于不区分大小写匹配文件名,并将文件名指定为“* .shp”,其中*与任何字符匹配,名称应以.shp结尾。

+0

等待这是在Objective-C? –

+0

我想这就是你要找的东西 - http://stackoverflow.com/questions/14110165/file-search-with-specific-extension-objective-c – Ajax1986

可以使用的NSFileManager删除文件:

NSFileManager * fileManager = [[NSFileManager alloc]init]; 

[fileManager removeItemAtPath:@"your path" error:nil]; 
+0

谢谢!但我不能给这个答案部分信用:第 –

你可以做到这一点通过以下方式:

NSURL *baseURL = [NSURL URLWithString:destinationPath]; 
NSDirectoryEnumerator* filesEnumerator = [[NSFileManager defaultManager] enumeratorAtURL:baseURL includingPropertiesForKeys:@[] options:0 errorHandler:nil]; 

NSURL* fileURL; 
while (fileURL = [filesEnumerator nextObject]) { 
    NSString* file = [fileURL lastPathComponent]; 
    BOOL match = [file containsString:@".shp"]; 
    if (match) { 
     [[NSFileManager defaultManager] removeItemAtURL:fileURL error:nil]; 
    } 
} 

请让我知道这是否解决了问题..