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.
- Click on the Advancesd... button.
- Select the Add Folders.
- Select the root folder of your project.
- Click on the OK button.