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:
您必须将文件名附加到目标目录 像(未经测试)的东西: 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) } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |