Backing a ResourceBundle with Properties Files Tips.
Java is very dynamic programing language. With thousands of APIs available for us to use, we do have a freedom of choice.
Some time back I’ve written an article on How to Read config.properties Values in Java? java.util.Properties
is very strong API to retrieve, update config properties values at runtime which I used in previously mentioned tutorial .
In this tutorial I’ll go over ResourceBundle.getBundle
API for the same. Properties file is used to store project specific settings, i.e.
- Common configs
- Database configs
- API configs
- Token configs
- System/Environment specific configs, i.e. prod, qa, etc
It’s very important to use properties file and you should use it most of the time if you need use some properties at multiple location which has dynamic value. Just update in config.properties
file and it you will get updated value at all the location.
In this tutorial we will name our config file to crunchify.properties
.
We are going to use public static final ResourceBundle getBundle(String baseName)
Above method gets a resource bundle using the specified base name, the default locale, and the caller's class loader
. Calling this method is equivalent to calling getBundle(baseName, Locale.getDefault(), this.getClass().getClassLoader())
.
Let’s get started:
Step-1
Create crunchify.properties
file with below contents:
#Crunchify Properties user=Crunchify.com company1=Google company2=eBay company3=Yahoo
Step-2
Put crunchify.properties
file under package crunchify.com.tutorials
, in the same package as your file CrunchifyReadConfigUsingResourceBundle.java
Step-3
Create file CrunchifyReadConfigUsingResourceBundle.java
package crunchify.com.tutorials; import java.util.Enumeration; import java.util.ResourceBundle; /** * @author Crunchify.com * */ public class CrunchifyReadConfigUsingResourceBundle { public static void main(String[] args) { try { ResourceBundle crunchifyResourceBundle = ResourceBundle.getBundle("crunchify.com.tutorials.crunchify"); Enumeration<String> crunchifyKeys = crunchifyResourceBundle.getKeys(); while (crunchifyKeys.hasMoreElements()) { String crunchifyKey = crunchifyKeys.nextElement(); String value = crunchifyResourceBundle.getString(crunchifyKey); System.out.println(crunchifyKey + ": " + value); } } catch (Exception e) { System.out.println("Error retrieving properties file: " + e); } } }
Step-4
Run the program and checkout result.
If you have list of below questions then also this tutorial will help: