我知道还有其他几个与此相关的问题......
- Class.getResource() 返回 null https://stackoverflow.com/questions/15581687/class-getresource-returns-null
- Java - class.getResource 返回 null https://stackoverflow.com/questions/4301329/java-class-getresource-returns-null
- 调用 context.getResources() 返回 null https://stackoverflow.com/questions/24374027/calling-context-getresources-returns-null
- getClassLoader().getResource(filepath) 返回空指针 https://stackoverflow.com/questions/8332371/getclassloader-getresourcefilepath-returns-a-null-pointer
但我的问题似乎有点不同,因为我似乎拥有避免出现此问题的所有必要条件。
代码:
this.getClass().getResource("checkstyle_whitespace.xml"); // null
问题是我已经通过检查调试器中的类加载器来验证我的类路径。这是我所看到的:
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/"
打击速度很快tree
我的目录结构。看build/resources
and src/main/resources
。当 gradle 构建我的项目时,正在复制这些文件。
├── 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
。如果我错了请纠正我...
如果您传递的资源路径不以/
to Class.getResource()
,类加载器在类的包中查找资源。不在根源。你的代码应该是
this.getClass().getResource("/checkstyle_whitespace.xml")
or
this.getClass().getClassLoader().getResource("checkstyle_whitespace.xml")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)