Skip to content

Yet another programming solutions log

Sample bits from programming for the future generations.

Technologies Technologies
  • Algorithms and Data Structures
  • Java Tutorials
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Spock Framework Tutorial
  • Spring Framework
  • Bash Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Developer’s Tools
  • Productivity
  • About
Expand Search Form

Java programmatic ResourceBundle – dynamic translations

farenda 2016-04-29 0

Java programmatic ResourceBundle – dynamic translations

In this tutorial we’re going to implement own ResourceBundle to show how to provide locale-sensitive values dynamically.

Own ResourceBundle implementation

ResourceBundle can be extended in a couple of ways. Here we extend it directly and supply Spanish language translations for a Map:

package com.farenda.java.util;

import java.util.*;

public class Words_es extends ResourceBundle {

    private static final Map<String, String> WORDS = new HashMap<>();
    static {
        // Load from some data source
        WORDS.put("book", "el libro");
        WORDS.put("date-format", "yyyy.MM.dd");
    }

    @Override
    protected Object handleGetObject(String key) {
        // Return null for unknown key to allow
        // check other Resource Bundles
        return WORDS.get(key);
    }

    @Override
    protected Set<String> handleKeySet() {
        // Faster implementation than default one
        return WORDS.keySet();
    }

    @Override
    public Enumeration<String> getKeys() {
        return Collections.enumeration(WORDS.keySet());
    }
}

Return null from handleGetObject(String key) if your ResourceBundle doesn’t know that key. This will make further searching of the key in more general bundles – like shown in Intro to ResourceBundles.

Overriding Set<String> handleKeySet() is optional and done only for performance reasons, because here we’ve got complete set of keys.

Default properties file Words.properties, located also in com.farenda.java.util path:

book=book
date-format=MM/dd/yyyy

Precedence of ResourceBundles – class vs properties file

If there are two resources with the same name of which one is a class and the other is properties file, for instance Words_es.class and Words_es.properties, then the class has higher precedence and properties file will not be loaded!

Using custom ResourceBundle

The above ResourceBundle is located in package com.farenda.java.util, so it has to be loaded from that path:

public static void main(String[] args) {
    Locale.setDefault(Locale.ENGLISH);
    displayWord("book", Locale.getDefault());
    displayWord("book", new Locale("es", "ES"));

    displayDate(Locale.CANADA);
    displayDate(new Locale("es", "ES"));
}

private static final String BUNDLE_NAME
        = "com.farenda.java.util.Words";

private static void displayDate(Locale locale) {
    ResourceBundle bundle = getBundle(BUNDLE_NAME, locale);
    String localeDate = formatDate(bundle.getString("date-format"));
    System.out.printf("19th May 2015 in locale '%s': %s%n",
            locale, localeDate);
}

private static String formatDate(String dateFormat) {
    Date date = Date.from(Instant.parse("2015-05-19T00:00:00.00Z"));
    return new SimpleDateFormat(dateFormat).format(date);
}

private static void displayWord(String word, Locale locale) {
    ResourceBundle words = getBundle(BUNDLE_NAME, locale);
    System.out.printf("'%s' in locale '%s': %s%n",
            word, locale, words.getString(word));
}

We get locale version of “date format” string and format the date accordingly. Notice that we use Instant from Java 8 to parse date string and then the new Date.from(Instant) to create old-style java.util.Date from it.

Now, when we run the above program it will print:

'book' in locale 'en': book
'book' in locale 'es_ES': el libro
19th May 2015 in locale 'en_CA': 05/19/2015
19th May 2015 in locale 'es_ES': 2015.05.19

References:

  • Collection to Enumeration
  • Java ResourceBundle – internationalized program
Share with the World!
Categories Java Tags java, java-util
Previous: Java ResourceBundle – internationalized program
Next: Java Initialization order

Recent Posts

  • Java 8 Date Time concepts
  • Maven dependency to local JAR
  • Caesar cipher in Java
  • Java casting trick
  • Java 8 flatMap practical example
  • Linked List – remove element
  • Linked List – insert element at position
  • Linked List add element at the end
  • Create Java Streams
  • Floyd Cycle detection in Java

Pages

  • About Farenda
  • Algorithms and Data Structures
  • Bash Tutorial
  • Bean Validation Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Java 8 Streams and Lambda Expressions Tutorial
  • Java Basics Tutorial
  • Java Collections Tutorial
  • Java Concurrency Tutorial
  • Java IO Tutorial
  • Java Tutorials
  • Java Util Tutorial
  • Java XML Tutorial
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Software Developer’s Tools
  • Spock Framework Tutorial
  • Spring Framework

Tags

algorithms bash bean-validation books clojure design-patterns embedmongo exercises git gof gradle groovy hateoas hsqldb i18n java java-basics java-collections java-concurrency java-io java-lang java-time java-util java-xml java8 java8-files junit linux lists log4j logging maven mongodb performance quartz refactoring regex rest slf4j solid spring spring-boot spring-core sql unit-tests

Yet another programming solutions log © 2021

sponsored
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.Ok