即使文件存在,Android / Kotlin中的java.lang.FileNotFoundException

问题描述 投票:-1回答:1

我有一个名为Contact的数据类,它具有一个伴随对象属性'allContacts:List',该属性在从JSON文件中解析联系人后返回联系人。

相关代码:

val allContacts: List<Contact>
            get() {
                val json = JSONObject(File("app/src/main/res/data/contacts.json").readText()).getJSONArray("contacts")
                val contacts = mutableListOf<Contact>()
                ...

我确实在res / data包中有一个contact.json。 (手动创建的数据包)。

这里是证据:

enter image description here

为什么会这样?最终的.apk文件中不包含contacts.json文件吗?

我尝试使用以下方式记录应用程序的当前路径

Log.i('.MainActivity', System.getProperty('user.dir'))

但是总是在Logcat中获得.。>>

编辑:我在Android Studio中反编译了apk,但没有发现contact.json的痕迹

我有一个名为Contact的数据类,它具有一个伴随对象属性'allContacts:List',该属性在从JSON文件中解析联系人后返回联系人。相关代码:val allContacts:List <...>

android json kotlin filenotfoundexception
1个回答
1
投票

您的文件与您期望的文件不在同一项目目录中。您必须创建资源目录raw,然后将文件粘贴到该目录中。然后,您可以在需要引用文件的任何地方将其引用为R.raw.contacts

© www.soinside.com 2019 - 2024. All rights reserved.