Search code examples
javalocalizationresourcebundle

Resource Bundle - anyone who care to explain?


Yet again I am asking something for my project and I pretty much feel like I am a total newb in Java... Anyway, I was recently told about ResourceBundle. My real problem is that I cannot understand the Oracle Documentation on the class in general and that I get some weird compile-time errors.
First off I made three Bundles mwb extends java.util.ResourceBundle, a second mwb_el extends mwb and a third mwb_en extends mwb. I made a contents variable of type Object[][] and wrote a method getContents() that return cotents;! Then I went into each class and changed the values for the second field in each line (not the key, the value). No I am stuck at a point that I cannot really get how to handle getting the values. I checked some tutorials and examples but I got even more confused. What I need is someone to explain to me:

  1. How do I make the mwb object I create and initialize in a class get the locale I want it to.

  2. How do I get a certain value. I tried getObject(), getString() even the getContents() and even overriden the handleGetObject() to no avail.

    Thanks in advance! :)


Solution

  • Property file should have messages in key/value pairs.

    e.g

    key1=message1
    key2=message2
    

    If you have a resource file called "MessagesBundle_en_US.properties" you can load it as follows.

    Locale locale = new Locale("en", "US");
    ResourceBundle messages = ResourceBundle.getBundle("MessagesBundle", locale);
    

    then messages.getString("key1") should return "message1".