java - 为什么 getResource 为 NULL?

标签 java android-studio intellij-idea resources

不是Android工程,是Android Studio中的Java库... File->New->New Module->Java Library

我尝试从资源文件夹中获取文件,但它始终为 NULL

    System.out.println("File is "+getClass().getClassLoader().getResource("google-services.json"));
    System.out.println("File is "+getClass().getClassLoader().getResource("/google-services.json"));
    System.out.println("File is "+getClass().getResource("google-services.json"));
    System.out.println("File is "+getClass().getResource("/google-services.json"));

结果文件为空

这是我的结构:

enter image description here enter image description here 运行配置 enter image description here

怎么了?为什么我无法从 res 文件夹中获取文件 google-services.json

更新: 似乎资源文件夹未添加到 java/build/classes/main 文件夹

因为System.out.println("文件是"+getClass().getClassLoader().getResource(""));

结果是 文件是 file:/D:/ProjectsHome/JavaFlat/java/build/classes/main/ enter image description here

最佳答案

通过将资源文件夹添加到依赖项来修复

按 F4-> 模块->您的模块-> 依赖项-> 添加“JAR 或目录”-> 选择 res 文件夹-> 类 https://stackoverflow.com/a/39289902/2425851

关于java - 为什么 getResource 为 NULL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40800270/

相关文章:

java - Websphere 中的 Eclipse Scout RAP UI 部署

java - registerReceiver() 显示重载方法的错误

android - 在 Android Studio 的布局设计器调色板中搜索组件

java - 如何在 IntelliJ 中使用现有的 Java 类型渲染器作为 Java 类型渲染器?

git - 在 IntelliJ IDEA、WebStorm、RubyMine 等中更改 GIT 登录名/用户名

intellij-idea - 如何从 Gradle 项目中的 Kotlin 类运行 main 方法?

java - 知道为什么我的 getColumnIndex() 通过 android 返回 -1 吗?

java - 找不到媒体类型为 : java. util.LinkedHashMap 的响应对象的 MessageBodyWriter:application/json

java - 无法在 Android Studio 中创建类文件

android - Android Studio 的 OpenCV 库错误