Java - Use ResourceBundle and properties files to add multilanguage support to your application

By xngo on February 27, 2019

The code below shows how to use ResourceBundle and properties files to add multilanguage support to your application.

The code

import java.util.Locale;
import java.util.Properties;
import java.util.ResourceBundle;
import java.io.FileOutputStream;
public class MultiLangualProperties
{
 
  public static void main(String[] args)
  {
    MultiLangualProperties oMp = new MultiLangualProperties();
    oMp.createProperties();
 
    // Load properties files.
    ResourceBundle oEnRBundle = ResourceBundle.getBundle("myproperties", Locale.ENGLISH);
    ResourceBundle oFrRBundle = ResourceBundle.getBundle("myproperties", Locale.FRENCH);
 
    String s = String.format("French equivalent of '%s' is '%s'.", oEnRBundle.getString("dog"), oFrRBundle.getString("dog"));
    System.out.println(s); // The output: French equivalent of 'dog' is 'chien'.
  }
  /**
   * Create all properties files.
   */
  public void createProperties()
  {
    this.createBaseProperty();
    this.createFrenchProperty();
  }
 
  /**
   * Create base properties file.
   */
  public void createBaseProperty()
  {
    // Create the properties object and add some values.
    Properties oWriteProperties = new Properties();
    oWriteProperties.setProperty("dog", "dog");
 
    // Save properties into file. 
    try
    {
      oWriteProperties.store(new FileOutputStream("myproperties.properties"), "Base properties");
    }
    catch(Exception ex)
    {
      System.out.println(ex.getMessage());
    }
  }
 
  /**
   * Create french properties file.
   */
  public void createFrenchProperty()
  {
    // Create the properties object and add some values.
    Properties oWriteProperties = new Properties();
    oWriteProperties.setProperty("dog", "chien");
 
    // Save properties into file. 
    try
    {
      oWriteProperties.store(new FileOutputStream("myproperties_fr.properties"), "French properties");
    }
    catch(Exception ex)
    {
      System.out.println(ex.getMessage());
    }
  }    
}

Note

If the properties are not placed at the right place, you will get the following error message: java.util.MissingResourceException Can't find bundle for base name, locale...

Here are the solutions:

1) Copy all properties into the build folder(e.g. bin\ folder)

or

2) In eclipse, add the root folder of your project in Run Configurations->Classpath->User Entries.

  1. Click on the Advancesd... button.
  2. Select the Add Folders.
  3. Select the root folder of your project.
  4. Click on the OK button.

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.