如何在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{
}
}
但我意识到,这只适用于文件。我正在尝试替换整个文件夹。
答案 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)