我正在
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.") } } }
从
copyItemAtPath(...)
documentation:
dstPath
The path at which to place the copy ofsrcPath
. 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) }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。