Move file and override [duplicate]

此生再无相见时 提交于 2019-12-10 14:16:02

问题


I'm trying to move a file even if a file with the same name already exists.

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

Does NSFileManager's method moveItemAtURL have an override option? How can I replace the existing file?


回答1:


You can always check if the file exists in the target location. if it does, delete it and move your item.

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)


来源:https://stackoverflow.com/questions/36295555/move-file-and-override

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!