首页 > 解决方案 > 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 {}
}

标签: swiftmacos

解决方案


您需要为目标指定完整的 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

推荐阅读