【发布时间】:2018-03-15 13:14:31
【问题描述】:
我正在尝试从路径(例如:“/Desktop/folder”)读取和写入文件。如果这无法完成,则从 Documents(例如:“/Documents/folder”)。我看到并尝试了几个示例,但问题是该文件位于以下位置:
file:///Users/name/Library/Developer/CoreSimulator/Devices/AE6A47DE-D6D0-49AE-B39F-25C7A2335DC8/data/Containers/Data/Application/09F890C1-081F-46E7-88BC-F8453BAFC1CB/Documents/测试.txt" 0x00006000000af780
即使我在文档甚至项目中都有“Test.txt”。
这是在上述位置读取和写入文件的代码:
let file = "Test.txt" //this is the file. we will write to and read from it
let text = "some text" //just a text
var text2 = ""
if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let fileURL = dir.appendingPathComponent(file)
//writing
do {
try text.write(to: fileURL, atomically: false, encoding: .utf8)
}
catch {/* error handling here */print(error)}
//reading
do {
text2 = try String(contentsOf: fileURL, encoding: .utf8)
}
catch {/* error handling here */ print(error)}
}
是否可以从我需要的路径读取和写入文件(例如:“文档/文件夹”)?
【问题讨论】:
-
您只能读取/写入某些“沙盒”目录,例如
Documents和Caches(或其中的子目录)。是的,您应该能够读取/写入Documents/Folder。编辑您的问题以显示执行此操作的代码,而不是上面的代码,它只是尝试写入Documents中的文件。 -
我没有从“文档/文件夹”读取的代码,这就是我需要的。
-
这太多了,无法集成到我的项目中。没有像我发布的从“文档/文件夹”读取文件的代码那样的简短版本吗?
-
是的。看我的回答。