filemanager.createFileAtPath 工作不正常
filemanager.createFileAtPath works not correctly
我尝试使用 NSFileManager
和方法 createFileAtPath
创建一个 PLIST 文件。最后,文件被创建,它的大小为 0 字节,我什至可以在 Finder 中看到该文件的特定 PLIST-Icon。
但是当我想打开它时(例如用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)")
}
reports.path = .../UserDir/.../Documents/Reports
非常感谢任何帮助。
filemanager.createFileAtPath
绝对正确,
但是您通过将一个空 NSData
对象写入磁盘来创建一个空文件。
NSData
对象未隐式序列化到 属性 列表。
要么使用 NSPropertyListSerialization
class 要么 – 更简单 – 将空字典写入磁盘。
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
例如pListURL
和 reportsURL
我尝试使用 NSFileManager
和方法 createFileAtPath
创建一个 PLIST 文件。最后,文件被创建,它的大小为 0 字节,我什至可以在 Finder 中看到该文件的特定 PLIST-Icon。
但是当我想打开它时(例如用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)")
}
reports.path = .../UserDir/.../Documents/Reports
非常感谢任何帮助。
filemanager.createFileAtPath
绝对正确,
但是您通过将一个空 NSData
对象写入磁盘来创建一个空文件。
NSData
对象未隐式序列化到 属性 列表。
要么使用 NSPropertyListSerialization
class 要么 – 更简单 – 将空字典写入磁盘。
let dictionary = NSDictionary()
let success = dictionary.writeToURL(pListPath, atomically: true)
print("Was file created?: \(success)")
print("plistPath: \(pListPath)")
PS:您不需要从 URL
创建 URLpListPath = reportsPath.URLByAppendingPathComponent("myReports.plist", isDirectory: false)
但我建议使用更具描述性的变量名称来区分 String
路径和 NSURL
例如pListURL
和 reportsURL