Search code examples
javafilejava-module

Loading files from subfolder of the resources folder in Java


I have a problem loading files from a subfolder in the resources folder of my IntelliJ Java 15 Gradle Project...

A representation of my project structure:

src/main/
├── java/
│   ├── AllMyClasses.java ... ... ...
│   └── module-info.java
└── resources/
    ├── text.txt
    └── img/
        └── favicon.png

And the relevant snippet of my code:

URL file = ClassLoader.getSystemResource("img/favicon.png");
URL file1 = ClassLoader.getSystemResource("text.txt");
System.out.println(file);
System.out.println(file1);

The output:

null
file:/C:/Users/MyUser/IdeaProjects/MyProject/build/resources/main/text.txt

Why does java only recognize the files DIRECTLY in the resources folder and not those in subfolders? How can I make my program also recognize those inside a subfolder?

Thanks to everyone who can help :)


Solution

  • I am not sure why your version is not working but here is what I use:

    getClass().getResourceAsStream("/img/favicon.png");
    

    Note: '/' in "/img" is necessary if your class is not in a default package (which it should not be)