In Java, dynamically add a line with a message to a properties file?

I can read the message from the properties file, where I added all the messages using key/valuepair

message.template.success.equipment.create = Equipment template created successfully
message.template.success.equipment.create.termination = Termination template created successfully
message.template.success.equipment.update = Equipment template updated successfully
message.template.success.termination.update = Termination template updated successfully

To read the message from the properties file, I created a class with the following code

public class PropertyReader {

    private static PropertyReader instance = null;
    private ResourceBundle bundleResource;
    private ResourceBundle bundleResourceMenu;
    private ResourceBundle bundleResourceMessage;
    private static final Logger log = Logger.getLogger(PropertyReader.class);

    private PropertyReader() {}

    private PropertyReader(Locale locale) {
        log.info("Property Reader loading files with locale : "+locale.getLanguage());
        bundleResourceMenu = ResourceBundle.getBundle("bsm-portal-menu",locale);
        bundleResource = ResourceBundle.getBundle("bsmResource",locale);
        bundleResourceMessage = ResourceBundle.getBundle("bsm-portal-message",locale);
        log.info("**** BundleResourceMessage *****");

    }

    public static synchronized PropertyReader getInstance(Locale locale) {
        if (instance == null)
            instance = new PropertyReader(locale);
        return instance;
    }


    public String getBundleResource(String propKey) {
        return this.bundleResource.getString(propKey);
    }

    public String getBundleResourceMenu(String propKey) {
        return this.bundleResourceMenu.getString(propKey);
    }

    public String getBundleResourceMessage(String propKey) {
        return this.bundleResourceMessage.getString(propKey);
    }


}

All this is normal.

Now I want this type of message dynamically

 message = "Entities " + appenMessage.toString() + " are already added in another association";

here the appenMessagevariable has a dynamically generated String value that I have to add with the message. Can this view be included in the properties file?

+4
source share
2 answers

Check out this tutorial about Compound Messages:

Personally, I try to do this with simple

 bundle.getString("key").replace("{0}", firstParam);
+2
source

The function is java.text.MessageFormat.format(pattern, argument…)designed specifically for this purpose.

:

message.template.entities.associated = Entities {0} are already added in another association

:

MessageFormat.format(getBundleResourceMessage("message.template.entities.associated"), appenMessage)

appenMessage.toString() {0}. MessageFormat , , .

+1

Source: https://habr.com/ru/post/1620855/


All Articles