ClassLoader.getResourceAsStream() confusion

1.3k Views Asked by At

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?

2

There are 2 best solutions below

1
On BEST ANSWER

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.'

1
On

Java uses several class loaders during runtime. It would be much simpler to use explicit file declaration instead of resources. Take a look on Commons Configuration.

On java class loaders you can read in Oracle official docs. If you pack configuration within your classes (into jar file) - you can use YourClass.class.getResourceAsStream(...). In other cases - prefer use explicit configuration file.

And yes, multiple calls to getResourceAsStream will load this resource multiple times. To clarify this take a look on java.net.URLClassLoader#getResourceAsStream sources.