繁体   English   中英

filemanager.createFileAtPath无法正常工作

[英]filemanager.createFileAtPath works not correctly

我尝试使用NSFileManager和方法createFileAtPath创建一个PLIST-File。 最后,创建了文件,文件大小为0字节,我什至可以在Finder中看到该文件的特定PLIST图标。 但是,当我想打开它(例如使用Xcode)时,它说: The data couldn't be read because it isn't in the correct format 我想写入此文件,但是当其格式不正确时,我将无法执行此操作。

文件创建有问题,但我不知道它是什么。 希望您能帮到我。 这是我的代码:

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

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

                if fileManager.fileExistsAtPath(pListPath.path!, isDirectory: &isDir)
                    {
                        print("File already exits")
                    }
                    else
                    {
                        let success = fileManager.createFileAtPath(pListPath.path!, contents: data, attributes: nil)

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

report.path = .../UserDir/.../Documents/Reports

非常感谢您的帮助。

filemanager.createFileAtPath绝对正确地工作,
但是您正在通过将一个空的NSData对象写入磁盘来创建一个空文件。
NSData对象不会隐式序列化到属性列表。

使用NSPropertyListSerialization类,或者-更简单-将空字典写入磁盘。

let dictionary = NSDictionary()
let success = dictionary.writeToURL(pListPath, atomically: true)
print("Was file created?: \(success)")
print("plistPath: \(pListPath)")

PS:您不需要从URL创建URL

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

但我建议使用更具描述性的变量名来区分String路径和NSURL例如pListURLreportsURL

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM