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