java.util.MissingResourceException:找不到基本名称'property_file name'的包,locale en_US

rog*_*hat 34 java properties resourcebundle

我正在尝试创建一个实用程序类,ReadPropertyUtil.java用于从属性文件中读取数据.虽然我的类位于util目录下,但我的skyscrapper.properties文件放在其他目录中.

但是,当我尝试使用属性访问时[ResourceBundle][1],我得到异常,无法加载该包.

下面是我如何阅读属性的代码,以及显示我的目录结构的图像.

ReadPropertiesUtil.java

/**
 * Properties file name.
 */
private static final String FILENAME = "skyscrapper";

/**
 * Resource bundle.
 */
private static ResourceBundle resourceBundle = ResourceBundle.getBundle(FILENAME);

/**
 * Method to read the property value.
 * 
 * @param key
 * @return
 */
public static String getProperty(final String key) {
    String str = null;
    if (resourceBundle != null) {
        str = resourceBundle.getString(key);
            LOGGER.debug("Value found: " + str + " for key: " + key);
    } else {
            LOGGER.debug("Properties file was not loaded correctly!!");
    }
    return str;
}
Run Code Online (Sandbox Code Playgroud)

目录结构

在此输入图像描述

这一行给出了错误 private static ResourceBundle resourceBundle = ResourceBundle.getBundle(FILENAME);

我无法理解为什么这不起作用,解决方案是什么.该src文件夹已完全添加到构建路径中.

Blu*_*zee 32

尝试使用资源的完全限定名称:

private static final String FILENAME = "resources/skyscrapper";
Run Code Online (Sandbox Code Playgroud)


Ros*_*rew 18

ResourceBundle不加载文件?您需要先将文件放入资源中.如何只是加载到FileInputStream然后加载PropertyResourceBundle

   FileInputStream fis = new FileInputStream("skyscrapper.properties");
   resourceBundle = new PropertyResourceBundle(fis);
Run Code Online (Sandbox Code Playgroud)

或者,如果您需要特定于语言环境的代码,那么这样的代码应该可行

File file = new File("skyscrapper.properties");
URL[] urls = {file.toURI().toURL()};
ClassLoader loader = new URLClassLoader(urls);
ResourceBundle rb = ResourceBundle.getBundle("skyscrapper", Locale.getDefault(), loader);
Run Code Online (Sandbox Code Playgroud)

  • 虽然我没试过,但似乎工作.好吧,上面的回答,使用完全限定的名称就可以了.并且看,不需要扩展.:) (2认同)

小智 6

使用资源就好

ResourceBundle rb = ResourceBundle.getBundle("com//sudeep//internationalization//MyApp",locale);
or
ResourceBundle rb = ResourceBundle.getBundle("com.sudeep.internationalization.MyApp",locale);
Run Code Online (Sandbox Code Playgroud)

只要给出合格的路径..它为我工作!!!


Ali*_*lah 5

你应该设置没有.properties扩展名的属性文件名,它对我来说是正常的:)