简体   繁体   中英

getClassLoader().getResourceAsStream() not work in modular java project (openjdk 11)?

this is a maven project , and have one image in resources directory :

├─ 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:

stream is null!
stream1 is null!

but when I remove module-info.java from project, will print:

stream is null!
stream1 is not null!

why? and how to use ClassLoader to load resources in modular java project?

Resources should be loaded over the Test.class , not its ClassLoader. By loading the resource over the class, you establish a context (JAR, module, dependencies) for where the resource is located.

For resources in the same package , use a relative path:

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).

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 . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM