Site icon

Internationalize/ Localize java application using locales/ ResourceBundle (example)

1. Project structure of project to support multiple languages is as follows:

  1. Create property file containing string for specific language & country code.
    1. e.g. Name of property file for language=English & country=USA will be <NAME>_en_us.properties
    2. Name of property file will be messages_en_US.properties
  2. Similarly, create properties for rest of languages & countries.
Fig 1: Project structure of Multilingual application

2. Internationalize/ Localize java application (ResourceBundle /example)

package org.learn;

import java.util.Locale;
import java.util.ResourceBundle;

public class DemoMultilingual {
    public static void main(String[] args) {

        ResourceBundle rd = ResourceBundle.getBundle("messages");

        //Display properties for language = english & Country = USA
        loadPropertiesByCountryAndLanguage("en","us");

        //Display properties for language = german & Country = germany
        loadPropertiesByCountryAndLanguage("de","DE");

        //Display properties for language = french & Country = france
        loadPropertiesByCountryAndLanguage("fr","FR");


        //Display properties for language = hindi & Country = india
        loadPropertiesByCountryAndLanguage("hi","in");
    }

    private static void loadPropertiesByCountryAndLanguage(String languageCode, 
                                                            String countryCode) {

        Locale locale = new Locale(languageCode,countryCode);
        ResourceBundle rd = ResourceBundle.getBundle("messages",locale);

        String propDescription = rd.getString("description");
        String propLanguage = rd.getString("Language");
        String propCountry = rd.getString("Country");

        System.out.printf("Loading properties for CountryCode=%s,LanguageCode=%s",
                                                    countryCode,languageCode);
        System.out.println();
        System.out.printf("Description=%s, Language=%s, Country=%s",
                                            propDescription,propLanguage,propCountry);
        System.out.println();
        System.out.println();
    }
}

3. OP: Internationalize/ Localize java application (ResourceBundle /example)

Loading properties for CountryCode=us,LanguageCode=en
Description=Localized strings for english language, Language=English, Country=USA

Loading properties for CountryCode=DE,LanguageCode=de
Description=Localized strings for german language, Language=German, Country=Germany

Loading properties for CountryCode=FR,LanguageCode=fr
Description=Localized strings for french language, Language=French, Country=France

Loading properties for CountryCode=in,LanguageCode=hi
Description=Localized strings for hindi language, Language=Hindi, Country=India

Download code-Internationalize/localize/multilingual java (example)

 

Exit mobile version