无法打开文件"xxx",因为没有这样的文件 [英] The file “xxx” couldn’t be opened because there is no such file
问题描述
我想打开一个.txt文件,并将内容另存为字符串.我试过了:
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)
打印结果:
file:///Users/Username/Documents/xxx.txt
但是我得到了错误:
The file "xxx.txt" couldn’t be opened because there is no such file
文件100%可用
注意:我使用的是Swift 4 for macOS
Notice: I working with swift 4 for macOS
推荐答案
您的 path
变量是 URL
,并且 path.absoluteString
返回URL的字符串表示形式(在您的情况下为字符串"file:///Users/Username/Documents/xxx.txt"
),而不是基础文件路径"/用户/用户名/文档/xxx.txt"
.
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"
.
使用 path.path
是一种可能的解决方案:
Using path.path
is a possible solution:
let path = ... // some URL
let contentString = try String(contentsOfFile: path.path)
,但是更好的方法是避免转换并使用基于URL的方法:
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)
这篇关于无法打开文件"xxx",因为没有这样的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!