【问题标题】:How can I retrieve a file path for file of a specific file extension?如何检索特定文件扩展名的文件的文件路径?
【发布时间】:2017-02-13 05:54:03
【问题描述】:

我已经解压了一个文件并发送到我的文档目录:

[SSZipArchive unzipFileAtPath:path toDestination:destinationPath];

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

我尝试了以下方法:

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

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

有什么想法吗?提前致谢。

【问题讨论】:

  • 请检查我的答案,如果它是你要找的,请告诉我

标签: ios objective-c


【解决方案1】:

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

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];

希望对你有帮助

【讨论】:

    【解决方案2】:

    您可以使用 NSFileManager 删除文件:

    NSFileManager * fileManager = [[NSFileManager alloc]init];
    
    [fileManager removeItemAtPath:@"your path" error:nil];
    

    【讨论】:

    • 谢谢!但我不能给这个答案部分功劳:p
    【解决方案3】:

    您可以通过以下方式进行:

    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];
        }
    }
    

    如果解决了问题,请告诉我..

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-22
      • 1970-01-01
      • 2015-04-19
      • 2011-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多