在Java中动态添加带有属性文件消息的字符串?

时间:2015-12-19 07:50:52

标签: java

我能够从属性文件中读取消息,其中我添加了key/value

的所有消息
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

从属性文件中读取消息我创建了一个包含以下代码的类

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);
    }


}

这一切都很好。

现在我想让这些类型的消息动态

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

这里appenMessage变量有一个动态生成的String值,我必须附加message.It是否可以将这种类型与属性文件合并?

2 个答案:

答案 0 :(得分:2)

查看本教程有关Compound Messages:

的信息

就个人而言,我倾向于用简单的

来做
 bundle.getString("key").replace("{0}", firstParam);

答案 1 :(得分:1)

java.text.MessageFormat.format(pattern, argument…)功能仅用于此目的。

在属性文件中:

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

在您的代码中:

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

这会导致appenMessage.toString()替换{0}占位符。 MessageFormat类还支持更高级别的占位符变体,以支持您在国际化中遇到的问题,例如复数化和日期格式化。