gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 10:03:13 25 4
gpt4 key购买 nike

如何在 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)

关于swift - 使用 Swift 替换文件系统中的文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37360728/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com