尝试将XML文件解析到我的Kotlin应用程序时遇到以下问题:
java.io.FileNotFoundException: /src/main/res/locations.xml: open failed: ENOENT (No such file or directory)
以下是负责处理文件加载的代码:
fun parseToObject() {
val thread = Thread(Runnable {
try {
val xml = File("src/main/res/locations.xml")
val doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xml)
println("Root Node: " + doc.documentElement.nodeName)
} catch (e: Exception) {
print(e.message)
}
})
thread.start()
}
有人知道我可能做错了吗?我尝试使用完整路径以及较短路径,但似乎不喜欢其中任何一个。
答案 0 :(得分:1)
您不能在运行时将项目文件作为文件访问,而只能作为InputStreams进行访问。而且,您不一定访问res
中的特定文件,除非它们位于res/raw/
中。否则,由于优化,它们甚至可能不存在于已安装的应用程序中。
您可以将文件放在main/res/raw/
或main/assets/
中。您可以将文件内容作为InputStream(而不是直接作为File)获得。
使用原始资源:
val doc = Resources.openRawResource(R.raw.locations).use { xmlInputStream ->
DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlInputStream)
}
println("Root Node: " + doc.documentElement.nodeName)
使用资产:
val doc = context.assets.open("locations.xml").use { xmlInputStream ->
DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlInputStream)
}
println("Root Node: " + doc.documentElement.nodeName)
原始资源与资产的优缺点:
原始资源具有ID,并且可以被其他资源XML文件引用。资产只能通过String文件名查找来访问,但是可以将它们组织到assets
中的子目录中。