getResource()在Gradle项目中返回null [英] getResource() is returning null with Gradle project

查看:95
本文介绍了getResource()在Gradle项目中返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道与此有关的还有其他问题...

I'm aware there are several other questions regarding this...


  • Class.getResource() returns null
  • Java - class.getResource returns null
  • Calling context.getResources() returns null
  • getClassLoader().getResource(filepath) returns a null pointer

但是我的问题似乎有所不同,因为我似乎拥有所有必要的东西而没有这个问题。

But my problems seems to be a bit different because I seem to have all of the necessary things to NOT have this problem.

代码:

 this.getClass().getResource("checkstyle_whitespace.xml"); // null

问题是我已经通过检查调试器中的类加载器来验证我的类路径。这是我所看到的:

The issue is that I've verified my classpath by inspecting the class loader in the debugger. Here's what I am seeing:

 27 = {URL@1235} "file:/Users/dennis/Documents/Development/java/java-grader/build/classes/main/"
 28 = {URL@1236} "file:/Users/dennis/Documents/Development/java/java-grader/build/resources/main/"

打击是我目录结构的快速。请参见构建/资源 src / main /资源。 gradle构建我的项目时,文件将被复制。

Blow is a quick tree of my directory structure. See build/resources and src/main/resources. The files are being copied when gradle builds my project.

├── build
│   ├── classes
│   │   ├── main
│   │   │   └── javaGrader
│   │   └── test
│   │       └── javaGraderTest
│   └── resources
│       └── main
│           ├── checkstyle_whitespace.xml
│           └── grammars
├── src
│   ├── main
│   │   ├── java
│   │   │   └── javaGrader
│   │   └── resources
│   │       ├── checkstyle_whitespace.xml
│   │       └── grammars
│   └── test
│       ├── java
│       │   └── javaGraderTest
│       └── resources
│           └── mini_test
├── target
│   ├── classes
│   ├── generated-sources
│   │   └── annotations
│   └── generated-test-sources
│       └── test-annotations
└── test_assets

据我所知,文件应该可以访问,因为它们位于 build 中。如果我错了,请纠正我...

From what I understand, the files should be accessible because they're in build. Correct me if I am wrong...

推荐答案

如果您传递的资源路径不是以<$ c开头$ c> / 到 Class.getResource(),类加载器会在类包中查找资源。不是根本。您的代码应该是

If you pass a resource path that doesn't start with a / to Class.getResource(), the class loader looks for the resource in the package of the class. Not at the root. Your code should be

this.getClass().getResource("/checkstyle_whitespace.xml")

this.getClass().getClassLoader().getResource("checkstyle_whitespace.xml")

这篇关于getResource()在Gradle项目中返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆