Loading with ResourceBundle from inside a jar

送分小仙女□ 提交于 2020-02-01 03:06:05

问题


I have seen some answers concerning how to load a particular file within a jar through getResourceAsStream, and I can manage this. However I am facing something really specific an I could not find an answer about this on the forum.

Here is the configuration:

I have a jar file having a conf directory that contains 2 properties files messages_en_US.properties and messages_fr_FR.properties. The classical way to load such resources is to use

ResourceBundle.getBundle("messages", java.util.Locale.getDefault());

If the files were on disk, in a directory referenced by the programm classpath, this works fine. But I don't know how I can manage combining use of ResourceBundle.getBundle and use of resources from witin a jar. Indeed, as I cannot see any bridge through getResourceAsStream (or this would imply managing locale by myself to specify the entire resource file name, wich is not very smart).

Can anyone help ?

Thanks.


回答1:


If it's in a conf directory inside the jar, then the package of the bundle you're trying to load is conf, and you should use

ResourceBundle.getBundle("conf.messages", java.util.Locale.getDefault());

The javadoc says:

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



回答2:


Have you tried this?

ResourceBundle.getBundle("conf/messages", java.util.Locale.getDefault());



回答3:


The ResourceBundle always search for a properties file, so, if you run :

ResourceBundle.getBundle("messages", java.util.Locale.getDefault());

The ResourceBundle will search for the "messages.properties" in your classpath.




回答4:


Assuming file messages.properties is part of some xyz.jar which is already on classpath of the project where you want to use this. Packaging of this file in jar is as below:

src
   |main
       |resources
            |com
                |xyz
                   ....|message.properties 

To read this file:

import java.util.ResourceBundle;

....

ResourceBundle.getBundle("com.xyz.resources.messages", Locale.getDefault());

Thanks



来源:https://stackoverflow.com/questions/10911708/loading-with-resourcebundle-from-inside-a-jar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!