简体   繁体   中英

How does Java ResourceBundle.getBundle load properties file?

I spent some time trying to load the properties file and couldn't find any solution that worked. Here is a picture of my setup.

Properties file location: /sandbox/resources/properties/MessageBundle_en_US.properties

App location: /sandbox/src/main/java/com/app/sandbox/App.java

在此处输入图片说明

Not sure what is going on. I tried several combinations, but it just can't get past the exception. I even tried entire path of the folder. Can anyone tell me how ResourceBundle.getBundle() method looks for properties files?

UPDATE 1: This solution stopped working a few minutes later:

ResourceBundle mybundle = ResourceBundle.getBundle("MessageBundle");

UPDATE 2: The solution above no longer worked during my last run. So I changed it to:

ResourceBundle mybundle = ResourceBundle.getBundle("properties/MessageBundle");

And it worked. It seems there might be a caching issue with how ResourceBundle looks for the properties file.

I am still not sure how ResourceBundle class looks for the properties file. It says to pass a "baseName" parameter:

baseName - the base name of the resource bundle, a fully qualified class name

https://docs.oracle.com/javase/7/docs/api/java/util/ResourceBundle.html#getBundle(java.lang.String)

But it's not clear how it starts looking for the files. Does it start looking from the root of the project directory? If someone can answer this, it would be good. What does it mean by a fully qualified class name . I wouldn't think "properties.MessageBundle" is fully qualified.

尝试如下使用;

ResourceBundle bundle = ResourceBundle.getBundle("properties/MessageBundle");

Yes, this should be the way:

R`esourceBundle mybundle = ResourceBundle.getBundle("MessageBundle");`

The reason that it can find it in the properties package without specifying the whole path, is because Java knows that the bundles by default should be in that package, and it doesn't need the other parts. So, if you use the whole path like: "/sandbox/resources/properties/MessageBundle" , Java will interpret it like:

"/sandbox/resources/properties/MessageBundle/sandbox/resources/properties/MessageBundle"

Which is clearly not correct. So, if you need to create more packages inside the properties package, just go from there and not from the root of your project.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM