问题
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