你可以做以下与Java ResourceBundle?

在属性文件...

example.dynamicresource=You currently have {0} accounts.

在运行时...

int accountAcount = 3;
bundle.get("example.dynamicresource",accountCount,param2,...);

得到的结果

"你目前有3个账户。"

有帮助吗?

解决方案

不是没有使用的MessageFormat 类,如:

String pattern = bundle.getString("example.dynamicresource");
String message = MessageFormat.format(pattern, accountCount);

其他提示

在他们自己的, ResourceBundle 不支持财产的占位符。通常的想法是采取串你获得自束,并坚持到 MessageFormat, ,然后使用该得到你的参数化的信息。

如果你使用 JSP/JSTL, 然后你可以结合 <fmt:message><fmt:param> 要做到这一点,它使用 ResourceBundleMessageFormat 根据涵盖。

如果你碰巧是使用 弹簧, 然后它有 ResourceBundleMessageSource不类似的东西, ,并且可以在任何地方使用你的节目。此 MessageSource 抽象(结合 MessageSourceAccessor)是更漂亮比 ResourceBundle.

有各种不同的方法,取决于查技术的使用。如果你使用"普通"Java(例如摆),那么使用 MessageFormat API作为回答之前。如果你使用拒绝服务框架(这是真的,如果我判断你的问题的历史,在这里正确的),那么这种方式取决于视技术和/或视的框架。如果例如"普通"JSP,然后可以使用JSTL fmt:message 这一点。

<fmt:message key="example.dynamicresource">
    <fmt:param value="${bean.accountCount}">
</fmt:message>

如果例如JSF,可以使用 h:outputFormat 这一点。

<h:outputFormat value="#{bundle['example.dynamicresource']}">
    <f:param value="#{bean.accountCount}">
</h:outputFormat>

最好的地方是只是咨询文件的技术/框架你使用(或者告诉这里所以,我们可以给更适合、更详细的答)。

Struts的有一个很好的util的所谓MessageResources这不正是你问......

e.g。

MessageResources resources = getResources(request, "my_resource_bundle"); // Call your bundle exactly like ResourceBundle.getBundle() method
resources.getMessage("example.dynamicresource",accountCount,param2,...);

<强>限制 它仅允许最大的3个参数(即资源属性,参数1,...,参数3)。

我建议使用的MessageFormat (如果你想使用3个以上参数值)由大卫·赛克斯的建议。

<强> PS getResources方法仅可在Struts Action类。

我不认为你可以做这项工作非英语属性文件。

我message.properties文件具有以下行:

<强> info.fomat.log.message.start =起始解析登录{0}格式消息。

和我的message_fr_FR.properties文件具有以下行:

<强> info.fomat.log.message.start = A partir D'分析器文件信息连接器{0}格式。

此代码的工作只对英语一个

<强>的String.format((字符串)消息.getString(GlobalConstants.MESSAGE_FORMAT_START),GlobalConstants.STR_JSON));

它确实不会:当我的语言/区域设置为法国替换值的占位符: - (

即使MessageFormat.fomat()是没有好处

我不相信的ResourceBundle能做到这一点本身,而是字符串可以:

String.format(bundle.getString("example.dynamicresource"), accountCount);

请记住,使用MessageFormat.format()当你需要的,如果你想表达的单引号('')在你的资源包使用双引号(')。

MessageFormoat#格式 会工作的情况下,如:

greetingTo=Have Param, saying hello {0}

你可以宣布两个方法,像这里RB是一个实例ResourceBundle:

/**This is a method that takes the param to substitute the placeholder**/
public String getString(String key, Object... params  ) {
    try {
        return MessageFormat.format(this.RB.getString(key), params);
    } catch (MissingResourceException e) {
        return "[" + key + "]";
    }
}

/**Without a param, this will derectly delegate to ResourceBundle#getString**/
public String getString(String key) {
    try {
        return this.RB.getString(key);
    } catch (MissingResourceException e) {
        return "[" + key + "]";
    }
} 
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top