当文件系统中不存在属性文件时,java ResourceBundle无法计算如何读取属性文件
我有一个EJB2.1应用程序,它引用一个属性文件来从中读取值。属性文件的文件名定义为
private static final String CONFIG_DIRECTORY = "config.";
private static final String PROPERTIES_FILE = CONFIG_DIRECTORY + "myapp";
要从属性文件中加载和读取属性,需要执行以下调用,将属性_文件作为propertyFileName的名称传入
this.getProperties(PROPERTIES_FILE);
getProperties
方法使用ResourceBundle加载属性文件,如下所示
public Properties getProperties (String propertyFileName) {
Properties properties = new Properties();
ResourceBundle resourceBundle = ResourceBundle.getBundle(propertyFileName);
Enumeration<String> keys = resourceBundle.getKeys();
while (keys.hasMoreElements()) {
String key = (String)keys.nextElement();
String value = resourceBundle.getString(key);
properties.put(key, value);
}
return properties;
}
现在我花了很多时间试图找到一个名为config的文件。myapp在应用程序的文件系统中无处不在,但它并不存在。我甚至在整个文件系统中搜索了那个文件,但它不在那里。我查看了所有文件夹、jar文件等,但找不到名为config的文件。myapp
在应用程序的根目录中有一个名为“config”的文件夹,在该文件夹中有一个名为myapp.properties
的文件,该文件确实具有应用程序正在读取的属性。是不是config.myapp
实际上指的是config/myapp.properties
文件?如果是这样的话,这是怎么回事?ResourceBundle
是否以某种方式将config.myapp
翻译成config/myapp.properties
# 1 楼答案
用斜线和附加线替换点。属性是预期的行为。从docs的
ResourceBundle.getBundle
中:# 2 楼答案
资源包。getBundle()从类路径加载,并执行complex logic来解析文件(资源)属性名称。是的,它补充道。属性,并使用包
简单地说,传递给getBundle()的字符串名为
basename
,逻辑是:因此,在您的情况下,如果您传递字符串“config.Myapp”,ResourceBundle将尝试从类路径加载其中一个资源(假设您有en_US locale):
这是因为ResourceBundle用于国际化(i18n),而不是用于配置
如果可以的话,我建议您查看一下我的小库来处理java属性:owner API。(希望这不是垃圾邮件)
# 3 楼答案
是的,当你使用
无需传递扩展名,也可以将路径作为“folder name.file name”传递
ResourceBundle将负责这些转换