【问题标题】:Replace folder in file system using Swift使用 Swift 替换文件系统中的文件夹
【发布时间】:2023-03-26 08:12:01
【问题描述】:

如何在 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{   
            }
        }

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

【问题讨论】:

    标签: swift cocoa swift2 filesystems nsfilemanager


    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-07
      • 2018-10-11
      相关资源
      最近更新 更多