移动文件并覆盖

Move file and override

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

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

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

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

Swift 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)