Swift:无法将文件复制到新创建的文件夹

问题描述 投票:5回答:1

我正在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文件,但随后导致“FAILED to add ...”,我做错了什么?

swift nsfilemanager
1个回答
10
投票

来自copyItemAtPath(...) documentation

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

您必须将文件名附加到copyItemAtPath()调用的目标目录。

像(未经测试)的东西:

let destPath = newMTSFolder.stringByAppendingPathComponent(element.lastPathComponent)
if NSFileManager.defaultManager().copyItemAtPath(fullElementPath, toPath: destPath, error: &err) {
     // ...

Swift 3/4更新:

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)
}
© www.soinside.com 2019 - 2024. All rights reserved.