Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getResourceAsStream returning null in Java 10

Tags:

java

java-10

I have an application that was working with Java 1.8.0 162 and I'm in the process of upgrading it to Java 10. One of the issues I'm having is that

appProperties.getClass().getResourceAsStream("/application.properties")

started returning null in Java 10. Any ideas why? appProperties is defined like this:

appProperties = new Properties();

and this happens in a static method, in case that's relevant.

The file is present in src/main/resources/application.properties. This happens whether I'm running in from IntelliJ or from the jar produced by Maven.

I tried adding:

<resources>
    <resource>
       <directory>src/main/resources</directory>
    </resource>
</resources>

to my pom.xml but that had no effect.

Printing the class path with:

System.getProperty("java.class.path")

yields, as the first entry:

C:\Users\pupeno\Documents\Dashman\code\dashman\target\classes

which contains application.properties.

like image 536
pupeno Avatar asked Apr 06 '18 23:04

pupeno


2 Answers

The class of that variable is a system class and it is loaded by a different class loader.

You should use one of your own classes.

like image 152
user207421 Avatar answered Oct 18 '22 02:10

user207421


I found a solution although I don't entirely understand why this works an the problematic line doesn't, but this works:

Application.class.getResourceAsStream("/application.properties")

where Application is just a class in my app.

Maybe this is related to the answer pointed to by ochi, and Application.class is using my class loader and appProperties.getClass() is using the system class loader. But why does it behave differently on differently on Java 8 vs 10 is not something that is apparent.

like image 21
pupeno Avatar answered Oct 18 '22 02:10

pupeno