0

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?

August
  • 12,410
  • 3
  • 35
  • 51
Ram Bavireddi
  • 1,139
  • 1
  • 19
  • 43

2 Answers2

0

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.

ursa
  • 4,404
  • 1
  • 24
  • 38
  • Thank you for sharing a link to apache `Commons Configuration`. But My question is different. If I call this `Thread.currentThread().getContextClassLoader().getResourceAsStream(resourceName);` multiple times, is the config file loaded multiple times? – Ram Bavireddi Nov 16 '14 at 04:22
0

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

Community
  • 1
  • 1
marcelv3612
  • 663
  • 4
  • 10
  • If I call this Thread.currentThread().getContextClassLoader().getResourceAsStream(resourceName‌​); multiple times, is the config file loaded multiple times? – Ram Bavireddi Nov 16 '14 at 04:22