使用ResourceBundle.getBundle()无法加载资源包,找不到名称为en_US的基本资源包。

3
我尝试加载属性文件时出现以下异常:
Caused by: java.util.MissingResourceException: Can't find bundle for base name /fontawesome/fontawesome, locale en_US

我正在使用一个Maven项目,我的属性文件位于src\main\resources\fontawesome\fontawesome.properties

我正在使用以下代码从JavaFX8主类加载此文件:

FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setResources(ResourceBundle.getBundle("/fontawesome/fontawesome.properties"));

尝试使用绝对路径失败,将文件重命名为fontawesome_en_US.properties或fontawesome_en.properties 也无效(如其他SO帖子中所建议的)。

FYI添加语言环境后缀例如“en”或“_en_US”无必要/不能解决您的问题,因为 ResourceBundle 将使用没有后缀的文件作为默认文件,如果找不到一个具有匹配后缀的文件。这个回答 解释了为什么绝对路径也不起作用。 - xlm
4个回答

3

需要在pom.xml中包含.properties文件:

<resources>
    <resource>
        <directory>src/main/resources</directory>
        <includes>
            <include>**/*.fxml</include>
            <include>**/*.css</include>
            <include>**/*.properties</include>
        </includes>
    </resource>
</resources>

正如 https://maven.apache.org/plugins/maven-resources-plugin/examples/resource-directory.html 所述,不需要像这样定义,因为Maven会在默认文件夹下查找资源。 - navylover

0

不要包含 .properties 扩展名。

ResourceBundle 尝试从当前类路径加载属性文件。

如果属性存储在子目录中,请使用“.”代替“/”。

ResourceBundle.getBundle("fontawesome.fontawesome")

我尝试了,但我仍然看到错误。我尝试使用.properties和不使用.properties两种方式。
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setResources(ResourceBundle.getBundle("fontawesome.fontawesome"));
由此引起:java.util.MissingResourceException: Can't find bundle for base name fontawesome.fontawesome, locale 'en_US'。
- user68883

0
这是我的经验: 如果在名称中加入“.”,那么ResourceBundle.getBundle()将会寻找一个类而不是属性文件。该类看起来应该像这样: import java.util.ListResourceBundle;
public class DataEncryptionStrings extends ListResourceBundle {
@Override
protected Object[][] getContents() {
    return new Object[][] {
        {"ErrorCreateKeystoreInstance", "an exception occurred creating the keystore instance"},
        {"ErrorLoadInitialKeystore", "an exception occurred loading the initial keystore"},
        {"ErrorLoadKeystore", "an exception occurred loading the keystore"},

它遵循命名约定:
{classname}.class 是默认类
{classname}_en_US.class 是英语美国类
{classname}_fr_FR.class 是法语类

如果名称中没有“.”但有“/”,则会查找属性文件。

如果名称中既没有“.”也没有“/”,我认为可以提供属性文件或ListResourceBundle。它将找到您提供的任何内容。不过,我不确定这种行为是否适用于所有虚拟机。

让我感兴趣并开始寻找解决方案的问题是,我的文件名中包含“.”。我相当确定我的问题是我实现了属性文件而不是ListResourceBundle类,并且使用包含“.”的文件名时,ResourceBundle.getBundle(name)会查找ListResourceBundle类。当我用“_”替换文件名中的“.”时,我就能够找到默认的ResourceBundle属性文件。

User68883似乎在使用绝对地址"/fontawesome/fontawesome.properties"而不是相对地址"fontawesome/fontawesome.properties"。另外,在ResourceBundle.getBundle中,名称和Locale中不要包含文件扩展名。这就是ResourceBundle自动为您完成的,它会通过解析过程获取资源目录中最适合设备Locale的资源。

0

你的语言属性文件应该以_en结尾,所以在你的情况下应该是fontawesome_en.properties,你应该使用ResourceBundle.getBundle("fontawesome.fontawesome")来加载它。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接