使用Swift替换文件系统中的文件夹

时间:2016-05-21 08:42:17

标签: swift cocoa swift2 filesystems nsfilemanager

如何在OS X上使用Swift复制和粘贴文件夹的全部内容?如果destinationPath已经包含该文件夹,那么它应该替换它。

我试过

let appSupportSourceURL = NSURL(string: appSupportSourcePath)
        let appSupportDestinationURL = NSURL(string: appSupportDestinationPath+"/"+appSupportFileName)

        if (fileManager.isReadableFileAtPath(appSupportSourcePath)){
            do {
            try fileManager.copyItemAtURL(appSupportSourceURL!, toURL: appSupportDestinationURL!)}
            catch{   
            }
        }

但我意识到,这只适用于文件。我正在尝试替换整个文件夹。

1 个答案:

答案 0 :(得分:1)

我知道Apple鼓励新代码使用URL来指定文件系统路径。但是NSFileManager是一个旧类,它仍然在旧的基于字符串的路径和新的基于URL的范例之间进行转换。试试这个:

let appSupportSourcePath = "..."
let appSupportDestinationPath = "..."

let fileManager = NSFileManager.defaultManager()
do {
    // Delete if already exists
    if fileManager.fileExistsAtPath(appSupportDestinationPath) {
        try fileManager.removeItemAtPath(appSupportDestinationPath)
    }
    try fileManager.copyItemAtPath(appSupportSourcePath, toPath: appSupportDestinationPath)

} catch {
    print(error)
}
使用NSURL

修改方法

let appSupportSourceURL = NSURL(fileURLWithPath: "...", isDirectory: true)
let appSupportDestionURL = NSURL(fileURLWithPath: "...", isDirectory: true)

try! NSFileManager.defaultManager().copyItemAtURL(appSupportSourceURL, toURL: appSupportDestionURL)