The file “xxx” couldn’t be opened because there is no such file [duplicate]

心已入冬 提交于 2021-02-08 13:04:24

问题


I would like to open a .txt file and save the content as a String. I tried this:

let path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("xxx.txt")
var contentString = try String(contentsOfFile: path.absoluteString)
print(path)

The print result:

file:///Users/Username/Documents/xxx.txt

But I get the error:

The file “xxx.txt” couldn’t be opened because there is no such file

The file is 100% available

Notice: I working with swift 4 for macOS


回答1:


Your path variable is an URL, and path.absoluteString returns a string representation of the URL (in your case the string "file:///Users/Username/Documents/xxx.txt"), not the underlying file path "/Users/Username/Documents/xxx.txt".

Using path.path is a possible solution:

let path = ... // some URL
let contentString = try String(contentsOfFile: path.path)

but the better method is to avoid the conversion and use the URL-based methods:

let path = ... // some URL
let contentString = try String(contentsOf: path)



回答2:


thx, I solved my problem. I have to use .path instead of .absoluteString:

var contentString = try String(contentsOfFile: path.path)


来源:https://stackoverflow.com/questions/46316256/the-file-xxx-couldn-t-be-opened-because-there-is-no-such-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!