【问题标题】:How to delete ALL FILES in a specified directory on the app?如何删除应用程序指定目录中的所有文件?
【发布时间】:2010-02-09 03:40:30
【问题描述】:

给定一个目录[[self documentsDirectory] stringByAppendingPathComponent:@"Photos/"]我如何删除这个文件夹中的所有文件?

(假设一个正确的文档目录路径)

【问题讨论】:

    标签: iphone objective-c cocoa-touch filesystems


    【解决方案1】:
    NSFileManager *fm = [NSFileManager defaultManager];
    NSString *directory = [[self documentsDirectory] stringByAppendingPathComponent:@"Photos/"];
    NSError *error = nil;
    for (NSString *file in [fm contentsOfDirectoryAtPath:directory error:&error]) {
        BOOL success = [fm removeItemAtPath:[NSString stringWithFormat:@"%@%@", directory, file] error:&error];
        if (!success || error) {
            // it failed.
        }
    }
    

    如果存在错误,我会让你做一些有用的事情。

    【讨论】:

    • 一般来说,您应该使用stringByAppendingPathComponent 而不是stringWithFormat 来连接路径。 (我知道上述方法有效,但这只是因为您在@"Photos/" 中硬编码的斜杠。)
    • Zekel 是正确的 - 使用 stringByAppendingPathComponent 很重要,特别是如果你在 iOS 上使用它。
    • 实际上上面的代码不起作用因为stringByAppendingPathComponent@"Photos/"中剥离了硬编码的斜线,这样当你稍后尝试使用directory变量时,它不包括应将其与file 分开的斜线。快速解决方法是在创建 directory 变量时删除硬编码的尾部斜杠,并将斜杠添加到 %@%@ 之间的 stringWithFormat 调用中
    • 您可能希望将[fm contentsOfDirectoryAtPath:directory error:&error] 移出for 循环,这样它就不会在每次迭代时调用该方法。类似NSArray<NSString*> *contents = [fm contentsOfDirectoryAtPath:documentsPath error:&error];for (NSString *file in contents)
    【解决方案2】:

    如果你想删除文件和目录本身,那么在没有for循环的情况下使用它

    NSFileManager *fm = [NSFileManager defaultManager];
    NSString *directory = [[self documentsDirectory] stringByAppendingPathComponent:@"Photos"];
    NSError *error = nil;
    BOOL success = [fm removeItemAtPath:cacheImageDirectory error:&error];
    if (!success || error) {
        // something went wrong
    }
    

    【讨论】:

      【解决方案3】:

      速成爱好者也一样:

      let fm = FileManager.default
      do {
        let folderPath = "...my/folder/path"
        let paths = try fm.contentsOfDirectory(atPath: folderPath)
        for path in paths
        {
          try fm.removeItem(atPath: "\(folderPath)/\(path)")
        }
      } catch {
        print(error.localizedDescription)
      }
      

      【讨论】:

      • 为我工作 谢谢 只需要稍作修改,谢谢
      【解决方案4】:

      大多数较旧的答案都让您使用contentsOfDirectoryAtPath:error:,这会起作用,但according to Apple

      “指定文件或目录位置的首选方法是使用 NSURL 类”

      所以如果你想使用 NSURL 代替,你可以使用方法contentsOfDirectoryAtURL:includingPropertiesForKeys:options:error:,所以它看起来像这样:

      NSFileManager *fileManager = [NSFileManager defaultManager];
      NSArray<NSURL*> *urls = [fileManager contentsOfDirectoryAtURL:directoryURL includingPropertiesForKeys:@[NSURLNameKey, NSURLIsDirectoryKey] options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];
      
          for (NSURL *url in urls)
          {
              NSError *error = nil;
              BOOL success = [fileManager removeItemAtURL:url error:error];
              if (!success || error) {
                  // something went wrong
              }
          }
      

      【讨论】:

        【解决方案5】:

        斯威夫特 4

          do {
        
                let destinationLocation:URL = ...
        
                if FileManager.default.fileExists(atPath: destinationLocation.path) {
                    try! FileManager.default.removeItem(at: destinationLocation)
                }
        
            } catch {
            print("Error \(error.localizedDescription)")
            }
        

        【讨论】:

        • 如果你使用的是catch,尝试后不应该强制。此外,您正在尝试按 URL 删除文件,而不是按路径删除所有文件。
        • 来自 Apple:“不建议尝试根据文件系统的当前状态或文件系统上的特定文件来判断行为”,这意味着您不应该在删除之前检查文件是否存在它。您应该尝试删除文件,然后适当地处理错误。在fileExists(atPath:) 上查看the documentation 了解更多信息。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-07
        • 2012-03-01
        • 2017-01-16
        • 1970-01-01
        • 1970-01-01
        • 2017-05-13
        相关资源
        最近更新 更多