Java – resource and configuration loading in Maven project
I'm using Maven for desktop applications I read about Maven standard directory layout, and now I have this project structure:
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 configuration files I read some articles and topics and found this (a simplified example in 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"); } }
However, the image and config variables contain null I'm trying different load variants (from the root folder, using this. GetClass () instead of preferences. GetClass) Class, and others), but I'm always null I really don't understand this resource loading system. I haven't found any good documents about it If someone has a good explanation of this mechanism (or just give a link on the document), it's great Therefore, the main question is: how to load my resources and configuration files?
Solution
I think I found a solution Just like juned Ahsan and Mr_ Fr0g, I need to use classloader class instead of this getClass(). getResource(). However, it only applies to resource folders However, Maven allows you to add other folders as resource folders I just need to add this section to POM xml:
<build> <resources> <resource> <directory>src/main/config</directory> </resource> </resources> </build>
And the working java code is:
InputStream image = this.getClass().getClassLoader().getResourceAsStream("images/image.png"); InputStream config = ClassLoader.getSystemResourceAsStream("config.xml");