gpt4 book ai didi

带逗号的 Java 资源包格式

转载 作者:行者123 更新时间:2023-12-04 04:58:45 24 4
gpt4 key购买 nike

我有一个 Web 服务实现,它验证请求并在响应中写入错误消息。响应不是所需的格式。

错误消息模板位于资源包属性文件中。
...key=Plant name {0} Plant Id {1}....
这是我在验证后收到的错误消息。
Plant name PLANT1 Plant Id 9,905,005.
但所需的输出是数字变量没有逗号。
Plant name WPLANT Plant Id 9905005.
这是我的代码。

private String getErrorMessage(String messageKey, Object... args) {
ResourceBundle messages = ResourceBundle.getBundle("ErrorMessageResourceBundle");
MessageFormat formatter = new MessageFormat("");
formatter.applyPattern(messages.getString(messageKey));
String output = formatter.format(args);
return output;
}

我正在使用 key 和变量调用此方法,如下所示。
...
getErrorMessage(key,"PLANT1",9905005)
...

如何更改此代码以获得所需的输出?我更喜欢不包含 %s, %d 的方法,从那以后我就无法更改属性文件中错误消息中变量的顺序。

最佳答案

您可以使用子格式模式。
示例:

MessageFormat formatter = new MessageFormat("{0} {1,number,###0}");

所以代码会是这样的:
private String getErrorMessage(String messageKey, Object... args) {
ResourceBundle messages = ResourceBundle.getBundle("ErrorMessageResourceBundle");
MessageFormat formatter = new MessageFormat("{0} {1,number,###0}");
formatter.applyPattern(messages.getString(messageKey));

String output = formatter.format(args);
return output;
}

在此处阅读 Oracle 关于 SubFormatPattern 的文档:
http://docs.oracle.com/javase/6/docs/api/java/text/MessageFormat.html#patterns

关于带逗号的 Java 资源包格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16410771/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com