fileManager.createFileAtPath总是失败

fileManager.createFileAtPath always fails

我尝试调用 fileManager.createFileAtPath 方法,但总是失败。 我的变量 success 始终是 false。我在这里查看了一些类似的帖子,但没有一个完全符合我的需要。 这是我的代码:

pListPath = NSURL(fileURLWithPath: String(reportsPath)).URLByAppendingPathComponent("myReports.plist", isDirectory: false)

                let data: NSData = NSData()
                var isDir: ObjCBool = false

            if fileManager.fileExistsAtPath(String(pListPath), isDirectory: &isDir)
                {
                    print("File already exists")
                }
                else
                {

                    let success = fileManager.createFileAtPath(String(pListPath), contents: data, attributes: nil)

                    print("Was file created?: \(success)")
                    print("plistPath: \(pListPath)")
                }

以下是我尝试解决此问题的方法:

我尝试使用方法

let success = NSFileManager.defaultManager().createFileAtPath(String(pListPath), contents: data, attributes: nil)

还有

let success = data.writeToFile(String(pListPath), atomically: true)

但没有任何效果。 success 总是 false。 我还尝试给它一个文字字符串作为路径,将 contents 设置为 nil 并且我什至将我想要将其放入的目录权限更改为 777,但注意是有效的。 success总是错误的。我希望你能帮我解决这个问题。 非常感谢任何帮助。谢谢

确保您尝试在已存在的文件夹中创建文件。 首先创建文件夹,然后你可以在该路径创建文件。

private class func assureDirPathExists(path: String)
{
    if !NSFileManager.defaultManager().fileExistsAtPath(path)
    {
        do {
            try NSFileManager.defaultManager().createDirectoryAtPath(path, withIntermediateDirectories: false, attributes: nil)
        } catch let error as NSError {
            print(error.localizedDescription)
        }
    }
}

确保您正在相对于用户域文件夹写入文件。

 // i.e. Caches, Documents...
 let rootPath = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true) 

可能是您遗漏了斜杠字符,或者您先跳过了一些文件夹创建。

如果您有 ...dir1/dir2/file.ext,则需要创建 dir1,然后是 dir2,最后是 file.ext.

这里有个问题:

if fileManager.fileExistsAtPath(String(pListPath), isDirectory: &isDir)

您不能使用 String(...)NSURL 转换为文件路径字符串, 你必须使用 path 方法:

if fileManager.fileExistsAtPath(pListPath.path!, isDirectory: &isDir)

如果 reportsPath 也是一个 NSURL 那么同样的问题存在于

pListPath = NSURL(fileURLWithPath: String(reportsPath)).URLByAppendingPathComponent("myReports.plist", isDirectory: false)

应该是

let pListPath = reportsPath.URLByAppendingPathComponent("myReports.plist", isDirectory: false)