有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

当文件系统中不存在属性文件时,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


共 (3) 个答案

  1. # 1 楼答案

    用斜线和附加线替换点。属性是预期的行为。从docsResourceBundle.getBundle中:

    Otherwise, getBundle attempts to locate a property resource file. It generates a path name from the candidate bundle name by replacing all "." characters with "/" and appending the string ".properties". It attempts to find a "resource" with this name using ClassLoader.getResource.

  2. # 2 楼答案

    资源包。getBundle()从类路径加载,并执行complex logic来解析文件(资源)属性名称。是的,它补充道。属性,并使用包

    简单地说,传递给getBundle()的字符串名为basename,逻辑是:

    The baseName argument should be a fully qualified class name. However, for compatibility with earlier versions, Sun's Java SE Runtime Environments do not verify this, and so it is possible to access PropertyResourceBundles by specifying a path name (using "/") instead of a fully qualified class name (using ".").

    因此,在您的情况下,如果您传递字符串“config.Myapp”,ResourceBundle将尝试从类路径加载其中一个资源(假设您有en_US locale):

    1. 配置。我的资源。阶级
    2. /config/Myapp。“财产”
    3. /config/Myapp_en。属性
    4. 配置。我的应用程序。阶级
    5. /config/Myapp_en_US。属性

    这是因为ResourceBundle用于国际化(i18n),而不是用于配置

    如果可以的话,我建议您查看一下我的小库来处理java属性:owner API。(希望这不是垃圾邮件)

  3. # 3 楼答案

    是的,当你使用

    ResourceBundle resourceBundle = ResourceBundle.getBundle(propertyFileName)
    

    无需传递扩展名,也可以将路径作为“folder name.file name”传递

    ResourceBundle将负责这些转换