Swift:无法将文件复制到新创建的文件夹 [英] Swift: failing to copy files to a newly created folder
问题描述
我正在 Swift 中构建一个简单的程序,它应该将具有特定扩展名的文件复制到不同的文件夹.如果这个文件夹存在,程序就将它们复制到文件夹中,如果文件夹不存在,程序必须先制作.
I'm building a simple program in Swift, it should copy files with a certain extension to a different folder. If this folder exist the program will just copy them in the folder, if the folder doesn't exist, the program has to make it first.
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 文件,但会导致添加失败...",我做错了什么?
Running this code will correctly identify the MTS files but then result in a "FAILED to add...", what am I doing wrong?
推荐答案
From the copyItemAtPath(...)
documentation:
dstPath
放置 srcPath
副本的路径.这条路必须在新位置包含文件或目录的名称....
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 及更高版本更新了代码)
You have to append the file name to the destination directory for the
copyItemAtPath()
call (code updated for Swift 3 and later)
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:无法将文件复制到新创建的文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!