【问题标题】:Swift: failing to copy files to a newly created folderSwift:无法将文件复制到新创建的文件夹
【发布时间】:2014-10-07 02:31:34
【问题描述】:

我正在用 Swift 构建一个简单的程序,它应该将具有特定扩展名的文件复制到不同的文件夹。如果该文件夹存在,程序只会将它们复制到该文件夹​​中,如果该文件夹不存在,则程序必须先创建它。

let newMTSFolder = folderPath.stringByAppendingPathComponent("MTS Files")

if (!fileManager.fileExistsAtPath(newMTSFolder)) {
    fileManager.createDirectoryAtPath(newMTSFolder, withIntermediateDirectories: false, attributes: nil, error: nil)
}

while let element = enumerator.nextObject() as? String {
    if element.hasSuffix("MTS") { // checks the extension
        var fullElementPath = folderPath.stringByAppendingPathComponent(element)

        println("copy \(fullElementPath) to \(newMTSFolder)")

        var err: NSError?
        if NSFileManager.defaultManager().copyItemAtPath(fullElementPath, toPath: newMTSFolder, error: &err) {
            println("\(fullElementPath) file added to the folder.")
        } else {
            println("FAILED to add \(fullElementPath) to the folder.")
        }
    }
}

运行此代码将正确识别 MTS 文件,但随后导致“添加失败...”,我做错了什么?

【问题讨论】:

    标签: swift nsfilemanager


    【解决方案1】:

    来自copyItemAtPath(...) documentation

    dstPath
    放置srcPath 副本的路径。这条路必须 在其新位置包含文件或目录的名称。 ...

    您必须将文件名附加到目标目录 copyItemAtPath() 调用(为 Swift 3 及更高版本更新代码)

    let srcURL = URL(fileURLWithPath: fullElementPath)
    let destURL = URL(fileURLWithPath: newMTSFolder).appendingPathComponent(srcURL.lastPathComponent)
    
    do {
        try FileManager.default.copyItem(at: srcURL, to: destURL)
    } catch {
        print("copy failed:", error.localizedDescription)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-03
      • 2010-10-28
      相关资源
      最近更新 更多