加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 02:26:00 所属栏目:百科 来源:网络整理
导读:我正在 Swift中构建一个简单的程序,它应该将具有特定扩展名的文件复制到另一个文件夹中.如果此文件夹存在,程序将只复制它们在文件夹中,如果该文件夹不存在,程序必须先将其复制. let newMTSFolder = folderPath.stringByAppendingPathComponent("MTS Files")i
我正在 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 …”,我做错了什么?

copyItemAtPath(...) documentation:

dstPath
The path at which to place the copy of srcPath. This path must
include the name of the file or directory in its new location. …

您必须将文件名附加到目标目录
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)
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读