2016-03-29 80 views
3

即使存在具有相同名稱的文件,也要移動文件。移動文件並覆蓋

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

NSFileManager的方法moveItemAtURL有一個覆蓋選項?我怎樣才能替換現有的文件?

+0

刪除目標文件,然後進行移動。 – EmilioPelaez

+1

很多objc都回答了這個問題。您可能可以將這些答案中的一部分轉換爲swift,例如http://stackoverflow.com/questions/6137423/how-to-overwrite-a-file-with-nsfilemanager-when-copying和http:// stackoverflow .COM /問題/ 20683696 /如何到覆蓋 - 一個用文件夾 - - 的NSFileManager-defaultmanager-,複印時 –

回答

6

您可以隨時檢查文件是否存在於目標位置。 如果有,請將其刪除並移動您的物品。

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 
    { 

    } 
} 
+0

這樣豈不更簡潔:'如果filemgr.fileExistsAtPath(LOCATION2) { 做 { 試filemgr.removeItemAtPath(LOCATION2) } 抓 {} } 做 { 嘗試filemgr.moveItemAtURL(LOCATION1,的toURL:LOCATION2) } ç atch { }' – KaraBenNemsi