Java ResourceBundle load resource for internationalization

Introduction

The following code shows how to use the ResourceBundle, ListResourceBundle, and PropertyResourceBundle classes.

SampleRB.java

import java.util.*;

// Default version (English).
public class SampleRB extends ListResourceBundle {
  protected Object[][] getContents() {
    Object[][] resources = new Object[3][2];

    resources[0][0] = "title";
    resources[0][1] = "My Program";

    resources[1][0] = "StopText";
    resources[1][1] = "Stop";

    resources[2][0] = "StartText";
    resources[2][1] = "Start";
  
    return resources;
  }//from  w w w.  ja  v  a 2s  .com
}

SampleRB_de.java

import java.util.*;
// German version.
public class SampleRB_de extends ListResourceBundle {
  protected Object[][] getContents() {
    Object[][] resources = new Object[3][2];

    resources[0][0] = "title";
    resources[0][1] = "Mein Programm";

    resources[1][0] = "StopText";
    resources[1][1] = "Anschlag";

    resources[2][0] = "StartText";
    resources[2][1] = "Anfang";
  
    return resources;
  }/*from ww  w  .jav a 2  s  . co m*/
}

The following code shows how to use resource bundle defined above.


// Demonstrate a resource bundle.
import java.util.*; 

public class Main { 
  public static void main(String args[]) { 
    ResourceBundle rd = ResourceBundle.getBundle("SampleRB");

    System.out.println("English version: ");
    System.out.println("String for Title key : " +
                       rd.getString("title"));

    System.out.println("String for StopText key: " +
                       rd.getString("StopText"));

    System.out.println("String for StartText key: " +
                       rd.getString("StartText"));

    rd = ResourceBundle.getBundle("SampleRB", Locale.GERMAN);

    System.out.println("\nGerman version: ");
    System.out.println("String for Title key : " +
                       rd.getString("title"));

    System.out.println("String for StopText key: " +
                       rd.getString("StopText"));

    System.out.println("String for StartText key: " +
                       rd.getString("StartText"));
  } /*from  ww  w.  ja  va  2s.  com*/
}



PreviousNext

Related