views:

1842

answers:

4

I'd like to eliminate dependencies on hardcoded paths for configuration data in my Java apps, I understand that using ResourceBundle will help me use the classloader to find resources.

Can someone tell me how I would replace a hardcoded path to a resource (say a .properties configuration data file required by a class) with appropriate use of ResourceBundle? Simple clear example if possible, thanks all.

+3  A: 

You will want to examine Resource.getBundle(String). You pass it the fully qualified name of a resource on the classpath to load as a properties file.

laz
A: 

The trick behind Resource.getBundle(..) is the use of the classloader. You can load everything thats in your classpath by accessing it via this.getClass().getClassLoader(). Resource.getBundle(..) is a practical helper to use it in the resource/locatization topic.

Toni Menzel
+2  A: 

Prior to Java 6, ResourceBundle typically allowed:

Java 6 comes with the ResourceBundle.Control class which opens the door to other sources of ResourceBundles, for example:

  • XML files (see example 2 in Javadoc)
  • Database rows

Hope this helps.

toolkit
+2  A: 

You don't need a ResourceBundle. A simple Properties object can do the job. Just use the classloader to get an inputstream for you properties file and use it to load de values. If you need to handle more sophisticated user configurations, use the preferences api.

Kind Regards

marcospereira