android - 从 androidTest 读取 json 文件
问题描述
您好,我正在尝试读取位于 androidTest 资源文件夹中的 json 文件。我可以访问位于 Test/resources 中的资源文件夹中的 json 文件,但不能访问 androidTest/resources 中的 json 文件。
我使用以下方法获取 Test/resources 文件夹中的 json 文件。
private fun getJson(path: String): String {
val uri = this.javaClass.classLoader?.getResource(path)
val file = File(uri?.path ?: "")
return String(file.readBytes())
}
解决方案
private fun getJson(fileName: Int): String {
val inputStream = InstrumentationRegistry.getInstrumentation().targetContext.resources.openRawResource(fileName)
val s = Scanner(inputStream).useDelimiter("\\A")
return if (s.hasNext()) s.next() else ""
}
推荐阅读
- c# - 如何将显示对象的“网格”翻转为 3x2 而不是 2x3
- mongodb - 如何在 grails 3.3.11 中为嵌入式域类使用动态查找器?
- kubernetes - ServiceAccount 无法在命名空间中列出资源“pod”,尽管它具有适当资源的角色
- c++ - 如何使用“clang-win”工具集构建调试提升静态库?
- sql - UPDATE 是更改表中最近的 DATETIME 条目的最简单方法吗?
- javascript - power bi 报告中的筛选器面板是否存在类似于 dataSelected 的事件?
- ruby - 如何在 factorybot 中为特征实现更新“批处理”
- java - 如何检查 Firebase 中的数据是否成功插入数组
- java - 如何将元素添加到不同类型的 Java 集合的 PriorityQueue 中?
- typescript - 为什么声明类型时可以在 redux 中未定义状态?