4

Im using Java resource bundles to localize my application and I have created a function which returns a message localized according to a resource bundle from a code... something like this:

public String getDescription(String code, ResourceBundle resBundle){
    String returnValue = null;  
    try{
        returnValue=resBundle.getString(code);
    }catch(Exception ex){
        returnValue = null;
    }
}

But, what I want to know if it is possible to add an entry to the resource bundle in case the code passed doesn't exist there, something like:

if(!resBundle.containsKey(code)){
    //This next line is pseudo-code... it is not valid at all
    resBundle.addEntry(code, "xyz");
}

Any help?

Pep Gomez
  • 197
  • 4
  • 14
  • 1
    `ResourceBundles` a are not really designed to be changed from code. The idea behind them is to provide a static map of codes to localized values. Can you explain why you want to add an entry to the resource bundle? Perhaps there is a different approach to solving your problem. – Christoph Böhme Aug 09 '17 at 11:25

1 Answers1

2

You can try to use Properties class and populate it by converting the ResourceBundle's keys to a Stream class, since Properties class functions like a Map with keys and values. For example :

Properties props = new Properties();
    resBundle.keySet().stream().forEach(k -> props.put(k, resBundle.getString(k)));

and then you can use the getProperty() method of Properties which returns the value you specify in the second argument in cases it doesn't find the key specified (in your case the key is code):

returnValue=props.getProperty(code,"xyz");
  • I don't understand your solution... it doesn't update the resource bundle with the key. I mean, what I need is to update the resource bundle adding the new key – Pep Gomez Aug 09 '17 at 09:42
  • I thought you could use a default value at runtime in cases you didn't find the key..Anyway i don't think you can modify values from `ResourceBundle `itself, it is used only for reading. But you can do it through `Properties` class, as mentioned : https://stackoverflow.com/questions/7571045/java-properties-add-new-keys-to-properties-file-in-run-time – Elton Hoxha Aug 09 '17 at 10:32
  • Thank you Elton... I wanted a way to track which entries were not in the resource, so I could, periodically, see which entries I had to update. What I have done is, with your method, have a parallel file were I save the entries not found. – Pep Gomez Aug 10 '17 at 12:00
  • Very well Pep.. If you find my answer helpful, please accept it. Thanks :) – Elton Hoxha Aug 11 '17 at 08:53