swift - FileManager.moveItem 的问题
问题描述
我有一个方法可以查看包含一堆 jpg 文件的目录(在 URL 处),这些文件的文件名以各种后缀(“_JpgFromRaw”、“_ThumbnailImage”、“_PreviewImage”等)结尾
jpg 文件将通过它们的后缀分成子文件夹(如果该名称的子文件夹不存在,则创建一个。)
我成功地创建了子文件夹,但是当我尝试将文件移动到它们各自的文件夹时,moveItem 会抛出“具有该名称的文件已经存在”的错误。所以没有文件被移动。
有人可以帮我找出我写的方法的问题吗?
谢谢你的任何建议。
func separateExtractedJPGsInDirectoryAtURL(url:URL) {
do {
let contents = try fm.contentsOfDirectory(at: url, includingPropertiesForKeys: [], options: [.skipsHiddenFiles])
// var dest : URL!
for file in contents {
let fileNameComponents : [String] = file.lastPathComponent.components(separatedBy: "_")
let jpgTypeWithExtension : [String] = fileNameComponents[fileNameComponents.count - 1].components(separatedBy: ".")
let jpgType : String = jpgTypeWithExtension[0]
let dest = url.appendingPathComponent(jpgType)
do {
try fm.createDirectory(at: url.appendingPathComponent(jpgType), withIntermediateDirectories: false, attributes: nil)
} catch {
do {
try fm.moveItem(at: file, to: dest)
} catch {print("error: \(error)")}
}
}
} catch {}
}
解决方案
您需要为目标指定完整的 URL,但您正在尝试将文件移动到目录(???)
do {
try fm.createDirectory(at: dest, withIntermediateDirectories: false, attributes: nil)
} catch {
do {
try fm.moveItem(at: file, to: dest.appendingPathComponent(file.lastPathComponent))
} catch {print("error: \(error)")}
}
并且您可能需要在尝试创建目录之前检查目录是否存在,因为它可能已经存在
func fileExists(atPath path: String) -> Bool
推荐阅读
- python - 在 3ds Max 中删除名为选择集的子对象层级。(蟒蛇/ maxscript)
- typescript - TS2345 错误 - X 类型的参数不可分配给 X[] 类型的参数
- docker - Github Actions:通过 gradle 任务推送 docker 镜像构建
- java - 通过工厂在 Java 中实例化多个不同类的更好方法
- swift - 如何向课堂 API 请求添加查询?
- python - Python中的直方图动画
- python - 尝试使用python中的日历模块创建多维数组
- python - 如何在 GCloud App 上安装 SQLite 和 CORS 等模块
- r - 有没有办法从 R 中的一组父子关系中获取 BOM 样式输出(SAP CS12)?
- jpa - 在共享 JAR 的 persistence.xml 中使用 EAR 级定义的数据源作为 JTA 数据源