URL resource = this.getClass().getResource("file-name") is null

242 views Asked by At

Completely puzzled. I do:

URL resource = this.getClass().getResource("eye-visible.png");

and the URL evaluates to null. "eye-visible.png" is a file in the same package as my class, which is "Controller.java":

enter image description here

I also tried (actually I started with this):

InputStream inputStream = Controller.class.getResourceAsStream("eye-visible.png");

and this returns null as well.

Really stuck - any clue??

This is a modular project and I run on the JDK14. I use NetBeans for an IDE. The lines above are in the start method of a JavaFX application. I reproduced the same null output with the lines above, in a new java project that has just a main class: same effect.

1

There are 1 answers

0
seinecle On BEST ANSWER

Thanks to the comment by @Andreas,

-> the non .java files were not copied to the location of the .class files (just ignored).

This is the consequence of using a Maven build, which has this behavior by default (only the files in src/main/resources will be copied to a separate location).

The fix is to add this fragment to the POM.xml (as per this answer to another question):

<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <excludes>
                <exclude>**/*.java</exclude>
            </excludes>
        </resource>
    </resources>
    <testResources>
        <testResource>
            <directory>src/test/java</directory>
            <excludes>
                <exclude>**/*.java</exclude>
            </excludes>
        </testResource>
    </testResources>
</build>