通过代码向 Java 资源包添加新条目
Add new entry to Java resource bundle from code
我使用 Java 资源包来本地化我的应用程序,并且我创建了一个函数,该函数 returns 根据来自代码的资源包本地化了一条消息...像这样:
public String getDescription(String code, ResourceBundle resBundle){
String returnValue = null;
try{
returnValue=resBundle.getString(code);
}catch(Exception ex){
returnValue = null;
}
}
但是,我想知道如果传递的代码在那里不存在,是否可以向资源包添加一个条目,例如:
if(!resBundle.containsKey(code)){
//This next line is pseudo-code... it is not valid at all
resBundle.addEntry(code, "xyz");
}
有什么帮助吗?
您可以尝试使用 Properties
class 并通过将 ResourceBundle 的键转换为 Stream
class 来填充它,因为属性 class 的功能类似于带有键和值的 Map
。例如:
Properties props = new Properties();
resBundle.keySet().stream().forEach(k -> props.put(k, resBundle.getString(k)));
然后您可以使用 Properties
的 getProperty()
方法,其中 returns 您在第二个参数中指定的值,以防找不到指定的键(在您的如果密钥是 code
):
returnValue=props.getProperty(code,"xyz");
我使用 Java 资源包来本地化我的应用程序,并且我创建了一个函数,该函数 returns 根据来自代码的资源包本地化了一条消息...像这样:
public String getDescription(String code, ResourceBundle resBundle){
String returnValue = null;
try{
returnValue=resBundle.getString(code);
}catch(Exception ex){
returnValue = null;
}
}
但是,我想知道如果传递的代码在那里不存在,是否可以向资源包添加一个条目,例如:
if(!resBundle.containsKey(code)){
//This next line is pseudo-code... it is not valid at all
resBundle.addEntry(code, "xyz");
}
有什么帮助吗?
您可以尝试使用 Properties
class 并通过将 ResourceBundle 的键转换为 Stream
class 来填充它,因为属性 class 的功能类似于带有键和值的 Map
。例如:
Properties props = new Properties();
resBundle.keySet().stream().forEach(k -> props.put(k, resBundle.getString(k)));
然后您可以使用 Properties
的 getProperty()
方法,其中 returns 您在第二个参数中指定的值,以防找不到指定的键(在您的如果密钥是 code
):
returnValue=props.getProperty(code,"xyz");