如何在OS X中移动文件并创建缺少的目录?

ixa*_*any 4 macos cocoa nsfilemanager swift2

我想将OSX中的文件移动到另一个目录:

func moveFile(currentPath currentPath: String, targetPath: String) {

let fileManager = NSFileManager.defaultManager()

do { try fileManager.moveItemAtPath(currentPath, toPath: targetPath) }
catch let error as NSError { print(error.description) }

}
Run Code Online (Sandbox Code Playgroud)

一切正常,除了目标目录不存在的情况。我发现这.isWritableFileAtPath可能会有所帮助。

但是,在声明的函数中,我使用完整的文件路径(包括文件名)。

我该如何从路径中分割文件名或从其他路径中分割文件名:如果需要,如何在移动文件之前强制Swift创建目录?

Cha*_* A. 5

过去,我已使用类似于以下代码的代码解决了此问题。基本上,您只是检查是否在表示要创建文件的父目录的路径中存在文件。如果它不存在,则创建它以及它上面路径中所有不存在的文件夹。

func moveFile(currentPath currentPath: String, targetPath: String) {
    let fileManager = NSFileManager.defaultManager()
    let parentPath = (targetPath as NSString).stringByDeletingLastPathComponent()
    var isDirectory: ObjCBool = false
    if !fileManager.fileExistsAtPath(parentPath, isDirectory:&isDirectory) {
        fileManager.createDirectoryAtPath(parentPath, withIntermediateDirectories: true, attributes: nil)

        // Check to see if file exists, move file, error handling
    }
    else if isDirectory {
        // Check to see if parent path is writable, move file, error handling
    }
    else {
        // Parent path exists and is a file, error handling
    }
}
Run Code Online (Sandbox Code Playgroud)

您可能还需要使用fileExistsAtPath:isDirectory:变体,以便处理其他错误情况。同样适用于