【问题标题】:Move file and override [duplicate]移动文件并覆盖[重复]
【发布时间】:2016-07-17 16:08:58
【问题描述】:

我正在尝试移动一个文件,即使已经存在同名文件。

NSFileManager().moveItemAtURL(location1, toURL: location2)

NSFileManager 的方法moveItemAtURL 是否有覆盖选项?如何替换现有文件?

【问题讨论】:

标签: ios swift file nsfilemanager


【解决方案1】:

您可以随时检查文件是否存在于目标位置。 如果是,请将其删除并移动您的项目。

斯威夫特 2.3

let filemgr = NSFileManager.defaultManager()

if !filemgr.fileExistsAtPath(location2) 
{
  do
  {
    try filemgr.moveItemAtURL(location1, toURL: location2)
  }
  catch
  {
  }
}
else
{
  do
  {
    try filemgr.removeItemAtPath(location2)
    try filemgr.moveItemAtURL(location1, toURL: location2)
  }
  catch
  {

  }
}

Swift 3+

try? FileManager.default.removeItem(at: location2)
try FileManager.default.copyItem(at: location1, to: location2)

【讨论】:

  • 这不是更简洁:if filemgr.fileExistsAtPath(location2) { do { try filemgr.removeItemAtPath(location2) } catch { } } do { try filemgr.moveItemAtURL(location1, toURL: location2) } catch { }
  • 对于 'Swift 3 及以上',您可以在这里查看答案stackoverflow.com/a/49854283/2641380,因为我们无法在这里回答。
猜你喜欢
  • 2012-02-05
  • 2012-12-09
  • 2023-04-09
  • 2017-12-25
  • 1970-01-01
  • 2012-01-29
  • 1970-01-01
  • 2019-12-17
  • 2011-11-17
相关资源
最近更新 更多