I am new to Java.
I have a requirement to load a configuration file (only one time, at app start up). What is the best way to do this? I have the following ideas:
Thread.currentThread().getContextClassLoader().getResourceAsStream(resourceName);
getClass().getClassLoader().getResourceAsStream(resourceName);
Out of these two which is the best and why?
Say for example, I have a method like below
public void loadConfig(String name) {
InputStream streamByContextClassLoader = Thread.currentThread().getContextClassLoader().getResourceAsStream(name);
}
If I call this method multiple times, is the config file loaded multiple times? Can any Please clarify my doubt?
I recommend using the first approach as it will work in cases when the second approach will not:
Thread.currentThread().getContextClassLoader().getResourceAsStream(resourceName);
I once initially used the second approach in a JUnit test and then we had to change it to use context class loader to allow running the test from IDE.
See: Difference between thread's context class loader and normal classloader , particularly this line
'In this case the object needs to use Thread.currentThread().getContextClassLoader() directly if it wants to load resources that are not available on its own classloader.'