我正在用 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 文件,但随后会导致“添加失败...”,我做错了什么?
最佳答案
来自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()
调用(针对 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)
}
关于Swift:无法将文件复制到新创建的文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47845268/