[英]getClassLoader().getResourceAsStream() not work in modular java project (openjdk 11)?
this is a maven project , and have one image in resources directory :这是一个maven 项目,在资源目录中有一个图像:
├─ src
├─ main
├─ java
└─ resources
└─imgs
└─logo.png
Code:代码:
public class Test {
public static void main(String[] args) {
InputStream stream = Test.class.getClassLoader().getResourceAsStream("/imgs/logo.png");
InputStream stream1 = Test.class.getClassLoader().getResourceAsStream("imgs/logo.png");
System.out.println(stream == null ? "stream is null!" : "stream is not null!");
System.out.println(stream1 == null ? "stream1 is null!" : "stream1 is not null!");
}
}
when I add module-info.java
to project, will print:当我将module-info.java
添加到项目中时,将打印:
stream is null!
stream1 is null!
but when I remove module-info.java
from project, will print:但是当我从项目中删除module-info.java
时,将打印:
stream is null!
stream1 is not null!
why?为什么? and how to use ClassLoader
to load resources in modular java project?以及如何使用ClassLoader
在模块化 java 项目中加载资源?
Resources should be loaded over the Test.class
, not its ClassLoader.资源应该通过Test.class
加载,而不是它的 ClassLoader。 By loading the resource over the class, you establish a context (JAR, module, dependencies) for where the resource is located.通过在 class 上加载资源,您可以为资源所在的位置建立上下文(JAR、模块、依赖项)。
For resources in the same package , use a relative path:对于同一 package 中的资源,请使用相对路径:
Test.class.getResource("logo.png")
If the qualified name of Test is org.foo.Test
, it would lookup the resource in org/foo/logo.png
in the JAR (or in the resources folder, before building the JAR).如果 Test 的限定名称是org.foo.Test
,它将在 JAR 中(或在构建 JAR 之前的资源文件夹中)的org/foo/logo.png
中查找资源。
For resources in the same module , use an absolute path, starting with a slash:对于同一模块中的资源,请使用以斜杠开头的绝对路径:
Test.class.getResource("/logo.png")
^ this is what you want to use most of the time. ^ 这是您大部分时间想要使用的。
There's no need to go over the classloader .不需要 go 超过 classloader 。 I see this often when developers are unaware of how to properly address a resource, and load the resource with a relative path but over the classloader , which works most of the time but not very well with modular projects/classloaders such as Java9 and OSGI.当开发人员不知道如何正确寻址资源并使用相对路径但通过类加载器加载资源时,我经常看到这种情况,这在大多数情况下都可以正常工作,但对于 Java9 和 OSGI 等模块化项目/类加载器来说并不是很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.