swift - 复制目标文件夹不存在的文件
问题描述
我正在编写一个应用程序来批量导入文件。我已经完成了大部分工作,但是当目标文件夹不存在时,该过程会停止。
这是代码的简化版本:
let fm = FileManager.default
do {
try fm.copyItem(atPath: "/…/source/file.ext",toPath: "/…/destination/NewFolder/file.ext")
}
catch let error as NSError {
print("Drat: \(error)")
}
在这种情况下,NewFolder
需要创建。如果我不这样做,我会收到如下消息:
Drat:错误域 = NSCocoaErrorDomain 代码 = 4“文件“file.ext”不存在。” UserInfo={NSSourceFilePathErrorKey=/.../source/file.ext, NSUserStringVariant=( Copy ), NSDestinationFilePath=/.../destination/NewFolder/file.ext, NSFilePath=/...source/file.ext, NSUnderlyingError=0x7fbaa9071270 {错误域= NSPOSIXErrorDomain Code=2 "没有这样的文件或目录"}}
我认为这意味着目标文件夹不存在,尽管从消息中并不明显。我发现如果我删除了NewFolder/
目标的一部分,文件就复制成功了。
如何快速创建缺少的目标文件夹。
我可能会补充说,作为批量复制,将创建多个缺少的目标文件夹。
解决方案
也许这是太复杂或太多的代码,但是您是否尝试过这种方式?
/// This method copies the objects in the pathList from the given sourceURL to the targetURL. If the object in the pathList is a folder the existence is being checked by calling
/// checkExistenceOf(path: String, at sourcePath: String, in targetPath: String). If the object is not a directory, the object is copied from the source to the target. The delegate is expected to
/// handle the conflict options set by the user.
/// - Parameters:
/// - sourceURL: The source folder from where the objects are being copied.
/// - targetURL: The target folder to where the objects need to be copied.
/// - pathList: The objects that need to be copied.
private func copy(sourceURL: URL, to targetURL: URL, with pathList: [String]) {
for path in pathList {
let fullSourceURL = sourceURL.appendingPathComponent(path)
let reportPath = path
let reportSource = fullSourceURL.lastPathComponent.replacingOccurrences(of: "%20", with: " ")
let reportTarget = targetURL.path
if fullSourceURL.hasDirectoryPath {
//The path is a directory and we are checking the existence.
checkExistenceOf(path: path, at: sourceURL, in: targetURL)
} else {
//The path is a file and we are going to copy it.
let fullTargetURL = targetURL.appendingPathComponent(path)
do {
try mainFileManager.manager.copyItem(at: fullSourceURL, to: fullTargetURL)
} catch {
print(error.localizedDescription)
}
}
}
}
然后使用这样的方法 checkExistenceOf() :
/// This method checks if a folder in the source location already exists in the target location. If the folder does not exist at the target, the folder is created by the method.
/// - Parameters:
/// - path: The folder that needs to be checked.
/// - sourcePath: The source location where the path already exists.
/// - targetPath: The target location where the existence of path is being chekced.
private func checkExistenceOf(path: String, at sourceURL: URL, in targetURL: URL) {
//The function fileExists can't deal with the %20 for space and the file:// for the source and target.
let sourcePath = sourceURL.relativePath
let targetPath = targetURL.relativePath
let fullSourcePath = String(sourcePath + "/" + path)
let fullTargetPath = String(targetPath + "/" + path)
//If the path doesn't exist create the folder at target with the same attributes as pth at source.
if !mainFileManager.manager.fileExists(atPath: fullTargetPath) {
let newDirectory = targetURL.appendingPathComponent(path)
do {
let attributes = try mainFileManager.manager.attributesOfItem(atPath: fullSourcePath)
try mainFileManager.manager.createDirectory(at: newDirectory, withIntermediateDirectories: false, attributes: attributes)
} catch {
print(error.localizedDescription)
}
}
}
代码来自以前的项目。我很抱歉没有擦洗它。
推荐阅读
- python - 在包含超过 1 个循环的字典中查找所有循环
- r - 如何使用 if_else 和 mutate 将字符向量中的值替换为条件?
- javascript - Javascript计算流的视频字节范围
- python - 我的解释器已被命令“git clean -d -f”删除
- mysql - 计算具有特定值的行之间的时间差
- django - 如何在 django 的基于类的视图中设置表单集
- android - 使用 AGP 7.0.0+ 可以替代“registerGeneratedResFolders”吗?
- python - Python 抓取特定的 JS 数据
- windows-installer - MSI 在重大升级期间在 ARP 中添加重复条目
- pine-script - 脚本触发警报不正确