Search code examples
javamavenresourcesclassloaderconfig

Resources and config loading in maven project


I'm using Maven for desktop build application. I read about Maven standard directory layout and I have this project structure for now:

App
|-- pom.xml
`-- src
    |-- main
        |-- java
        |   `-- java classes
        |-- resources
        |   `-- images
        |       `-- app images
        `--config
           `--config.xml

I want to find a way to load my resources and config files. I read some articles and topics and found this (simplified example from my code):

//class for loading config
public class Preferences {
    public Preferences() {
        InputStream image = Preferences.class.getResourceAsStream("images/image.png");
        InputStream config = Preferences.class.getResourceAsStream("config.xml");
    }        
}

But image and config variables contains null. I was trying different variants of loading (from root folder, with this.getClass() instead of Preferences.class, and others), but it's always null. I really don't understand this resource loading system and I didn't find any good documentation about it. It would be nice, if somebody gives a good explanation about this mechanism (or just give a link on docs). So, the main question is: How can I load my resources and config files?


Solution

  • I think I found the solution. As Juned Ahsan and mR_fr0g write, I need to use ClassLoader class, instead of this.getClass().getResource(). But, it works only for resource folder. But maven allows to add other folders as resource folders. I was just needed to add this section to pom.xml:

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

    And working java code is:

    InputStream image = this.getClass().getClassLoader().getResourceAsStream("images/image.png");
    InputStream config = ClassLoader.getSystemResourceAsStream("config.xml");