Home  >  Core Java

Example of ResourceBundle in Java

By Arvind Rai, June 09, 2013
java.util.ResourceBundle loads the bundles locale specific. If our program should run on the basis of user locale, ResourceBundle should be used. We need to create Resources by extending ListResourceBundle. Inside the method getContents, define the keys and values. ResourceBundle's object is obtained by calling getBundle. ResourceBundle is an abstract class. Find the example to use ResourceBundle.
SampleResources.java
package com.concretepage.util;
import java.util.ListResourceBundle;
public class SampleResources extends ListResourceBundle {
    protected Object[][] getContents() {
        return new Object[][] {
            {"user.name","Ram"},
            {"user.age","21"},
            {"user.city","Varanasi"}
        };
    }
}
ResourceBundleDemo.java
com.concretepage.util;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Locale;
import java.util.ResourceBundle;
public class ResourceBundleDemo {
    public static void main(String[] args) throws FileNotFoundException, IOException {
        ResourceBundle rb = ResourceBundle.getBundle("com.util.SampleResources", Locale.ENGLISH);
        Enumeration<String> en = rb.getKeys();
        while(en.hasMoreElements()){
            String key= en.nextElement();
            System.out.println("key:"+ key +" Values:"+rb.getString(key));
        }
    }
}
Output
key:user.age Values:21
key:user.name Values:Ram
key:user.city Values:Varanasi 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us