I have a configuration file in xml format, that I need to load into my java code. While testing, I have imported it through it's absolute URL, but now I am about to compile and deploy the project as a jar, and that won't work anymore.
From previous experience, I think the right way to do this, is to use the ClassLoader, but I'm having some difficulties. Maybe because of my project setup, I do not know. I think I would be able to make this work, as I ahve done in the past, but I really want to make sure I do it the standard, conventional and/or correct way, so that I do not need to experiment every single time this comes up.
Here is the code I've tried to implement: http://www.mkyong.com/java/java-read-a-file-from-resources-folder/
However, this code:
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("file/test.xml").getFile());
I could not use, due to needing the file in a static method of an abstract class. Therefor I switched it out with the following code:
ClassLoader classLoader = XmlConfigLoader.class.getClassLoader();
File file = new File(classLoader.getResource("configuration.xml").getFile());
The XmlConfigLoader is the containing Class. "configuration.xml"
is located in the src/main/resources
-folder, just as "file/test.xml"
is in the example
I've run the code in debug-mode, and found that the file
has the wrong path. Instead of looking in src/main/resources
, it points to target/classes
- Is there a setting option for default resource folder that I need to set?
- Is src/main/resources the conventional place to store files like this?
- Is my way of loading the ClassLoader correct in this setting?
As an additional info, this is a Maven project.
UPDATE:
My Current code actually works perfectly, apart from a single bug. The file is automatically transferred to the target/classes
folder at compile time. However, whitespaces in the url are replaced by %20
, and I have to manually change them back in order to make the system find the file. I am sure there is a better solution to this. Anyone?