Create Resource Bundle in the java code

Ads
 

Create Resource Bundle in the java code

Tutorial on Creating Resource Bundle in the java code

Tutorial on Creating Resource Bundle in the java code

Create Resource Bundle in the java code

     

This Example shows you how to create resource bundle. In the code given below we are create resource bundle for a locale.

Methods used in this example are described below :

ResourceBundle.getBundle() : ResourceBundle class object holds locale-specific objects. When a program needs a locale-specific resource on that time program can load locale from the resource bundle that is suitable for the current user's locale. Method getBundle() returns a ResourceBundle class object using the specified name and locale.

 

ResourceBundleExample.java


import java.util.*;

public class ResourceBundleExample {

  public static void main(String args[]) {
  try {
  Locale[] locales = new Locale[]{
  new Locale("fr""FR")new Locale("en""IN")
  };
  ResourceBundle bundle = null;
  for (int i = 0; i < locales.length; i++) {
  bundle = ResourceBundle.getBundle("Resource", locales[i]);

  System.out.println(locales[i].getDisplayName());
  System.out.println(bundle.getString("Hello"));
  System.out.println(bundle.getString("Goodbye")+"\n");
  }

  catch (Exception e) {
  System.out.println(e);
  }
  }
}

Resource.java 
import java.util.*;

public class Resource extends java.util.ResourceBundle {
  
  String keys = "Hello Goodbye";

  public Object handleGetObject(String key) {
  if (key.equals("Hello")) {
  return "Hello";
  }
  if (key.equals("Goodbye")) {
  return "Goodbye";
  }
  return null;
  }

  public Enumeration getKeys() {
  StringTokenizer key = new StringTokenizer(keys);
  return key;
  }
}

Resource_en_IN.java
import java.util.*;

public class Resource_en_IN extends Resource{

  public Object handleGetObject(String key) {
  if (key.equals("Goodbye")) return "Have a nice day ...";
 if (key.equals("Hello")) return "Hi, How are you ...";

  return null;
  }
}

Resource_fr_FR.java
import java.util.*;

public class Resource_fr_FR extends Resource{

  public Object handleGetObject(String key) {
  if (key.equals("Goodbye")) return "Au Revoir";
 if (key.equals("Hello")) return "Bonjour";

  return null;
  }
}

Output :
French (France)
Bonjour
Au Revoir

English (India)
Hi, How are you ...
Have a nice day ...

Download code

     

Ads

Ads